189. 轮转数组
自己写的老拉了
class Solution {
public:
void rotate(vector<int>& nums, int k) {
const int n = nums.size();
int ans[100010] = {};
for (int i = 0; i < n; ++i)
ans[(i + k) % n] = nums[i];
for (int i = 0; i < n; ++i)
nums[i] = ans[i];
}
};
看了卡哥思路,真是刘姥姥进大观园了,长见识了。
卡哥代码:
class Solution {
public:
void rotate(vector<int>& nums, int k) {
k = k % nums.size();
reverse(nums.begin(), nums.end());
reverse(nums.begin(), nums.begin() + k);
reverse(nums.begin() + k, nums.end());
}
};