Accepted Java iterative solution


  • 0
    O
    public void rotate(int[] nums, int k) {
        	if (k < 1 || nums.length <= 1 || k == nums.length) {
        		return ;
        	}
    		k = k%nums.length;
        	int n = nums.length, i, temp;
            for(i = 0; i < n; i+= k) {
                if (i + k > n) {
                    k = k%(n-i);
                }
                if (k == 0) {
                	break;
                }
            	for(int head = i, tail = n - k; head < tail && tail < n; head++, tail++) {
            		temp = nums[head];
            		nums[head] = nums[tail];
            		nums[tail] = temp;
            	}
            }
        }

Log in to reply
 

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