C++ solution - O(1) space


  • 0
    S
    class Solution {
    public:
        void rotate(vector<int>& nums, int k) {
            int i = k, j = 0;
            int ll = nums.size();
            int re = nums[0];
            int tmp;
            if(k >= ll)k = k%ll;
            int up = k;
            while(j<up){
                re = nums[j];
                i = j+k;
                if(i>=ll)i=i-ll;
                while(true){
                    if(i>j && i<up)up = i;// the most important line
                    tmp = nums[i];
                    nums[i]=re;
                    re = tmp;
                    if(i == j)break;
                    i = i+k;
                    if(i>=ll)i = i-ll;
                }
                j++;   
            }    
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.