My solution to rotate array in-place


  • 0
    B

    My code is not very standard. Welcome to modify it

    public void rotate(int[] nums, int n, int k) {
    		k = k % n;
    		if(k <= 0) return;
    		
    		int start = 0;
    		int ele = nums[start];
    		int temp;
    		int i = start;
    		int loop = 0;
    		while(loop++ < n) {
    			if((i + k) % n == start) {
    				nums[start] = ele;
    				start ++;
    				i = start;
    				if (start > n) break;
    				else {
    					ele = nums[start];
    					continue;
    				}
    			}
    			temp = nums[(i + k) % n];
    			nums[(i + k) % n] = ele;
    			ele = temp;
    			i = (i + k) % n;
    		}
    	}

  • 1
    S

    even i did in the similar way but i used extra space to keep track of un-swapped and swapped ones which is actually not necessary ,

    void rotate(int nums[], int n, int k) {
            k %= n;
            if(k==0 || n==0)
              return;
            bool set[n];
            memset(set,false,n);
            int mover = 0;
            int mod = n;
            int save = nums[mover];
            while(mod>0){
                 int index = (mover + k) % n ;
                 if(!set[index]){
                     set[index]=true;
                     int temp =nums[index];
                     nums[index]=save;
                     mover=index;    
                     mod--;
                     save=temp;
                 }
                 else{
                     mover = index+1;
                     save=nums[mover];
                 }
             }
        }

Log in to reply
 

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