189. 轮转数组
class Solution {
public:void rotate(vector<int>& nums, int k) {int len=nums.size();vector<int> num(len);for(int i=0;i<len;i++){num[(i+k)%len]=nums[i];}nums.assign(num.begin(),num.end());}
};
旋转数组
没看出数学公式gg
正确答案
class Solution {
public:int maxRotateFunction(vector<int>& nums) {int f = 0, n = nums.size();int numSum = accumulate(nums.begin(), nums.end(), 0);for (int i = 0; i < n; i++) {f += i * nums[i];}int res = f;for (int i = n - 1; i > 0; i--) {f += numSum - n * nums[i];res = max(res, f);}return res;}
};
超时答案
class Solution {
public:int maxRotateFunction(vector<int>& nums) {int len=nums.size();int max=0x80000000;for(int i=0;i<len;i++){int sum=0;for(int j=0;j<len;j++){sum+=nums[j]*((j+i)%len);}if(sum>max){max=sum;}}return max;}
};