leetcode-189

https://leetcode-cn.com/problems/rotate-array/

思路:先整体翻转,然后再分别翻转

void rotate(vector<int>& nums, int k) {
    k = k % nums.size();
    int left = 0, right = nums.size() - 1;
    while(left < right) {
        swap(nums[left], nums[right]);
        left += 1, right -= 1;
    }
    left = 0; right = k - 1;
    while(left < right) {
        swap(nums[left], nums[right]);
        left += 1, right -= 1;
    }
    left = k, right = nums.size() - 1;
    while(left < right) {
        swap(nums[left], nums[right]);
        left += 1, right -= 1;
    }
}

 

上一篇:Java中Comparable与Comparator的区别以及PriorityQueue的使用


下一篇:2021-09-29