Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7]
is rotated to [5,6,7,1,2,3,4]
.
思路:就用三部反轉法,
把原數據切兩分 1,2,3,4 5,6,7,
然後分別對這兩堆反轉變成 4,3,2,1 7,6,5
在一起反轉 5,6,7,1,2,3,4
class Solution {
public:
void rotate(vector<int>& nums, int k) {
if(k == 0 || (nums.size() == k) ) {
return;
}
if(k > nums.size() && k != 1) {
k = k%nums.size();
}
reverse(nums.begin(), nums.end()-k);
reverse(nums.end()-k, nums.end());
reverse(nums.begin(), nums.end());
}
};