【leetcode】189. Rotate Array 旋转数组

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation: 
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

    需求是将数组后k个数字移动到数组前面去,本身题目不难,但是要在原数组上完成序列翻转,还是需要想一下的。

解法一(naive approach),用栈保存后k个数字,然后移动前n-k个数字,左后完成拼接。

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        int nlen=nums.size();
        // 对k数字取余
        k%=nlen;
        stack<int>sta1;
        int i=1;
        while(i<=k){
            sta1.push(nums[nlen-i]);
            i++;
        }
        for(int i=1;i<=(nlen-k);i++){
            nums[nlen-i]=nums[nlen-k-i];
        }
        i=0;
        while(sta1.size()>0){
           nums[i]=sta1.top();
           sta1.pop();
           i++;
        }
        return; 
    }
};

解法二: 在原数组上操作。

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
    
    int n=nums.size();
    k=k%n;
    if(k==0 || n==1)
        return;
    reverse(nums, 0, n-k-1);
    reverse(nums, n-k, n-1);
    reverse(nums, 0, n-1);
 return;
}

void reverse(vector<int>& nums, int low, int high) {
    while(low<high) {
        int temp=nums[low];
        nums[low]=nums[high];
        nums[high]=temp;
        low++;
        high--;
    }
}
};

  以[1,2,3,4,5,6,7],k=3 为例子:

第一次reverse后 [4,3,2,1,5,6,7]

第二次reverse后 [4,3,2,1,7,6,5]

第三次reverse后 [5,6,7,1,2,3,4]

上一篇:刷题-链表


下一篇:刷题记录:538. 把二叉搜索树转换为累加树