My Easy Understanding Java Solution


  • 0
    public void rotate(int[] nums, int k) {
        k %= nums.length;
        if(nums==null || nums.length<2 || k==0) return;
        
        int indexOriginal=0, index=0, desIndex, tmp, source=nums[0], count=0;
        while(count < nums.length) {
            desIndex = (index+k)>nums.length-1 ? (index+k-nums.length) : index+k;
            tmp = nums[desIndex];
            nums[desIndex] = source;
            source = tmp;
            index = desIndex;
            count++;
            if(index == indexOriginal) {
                index++;
                indexOriginal = index;
                source = nums[index];
            }
        }
    }

Log in to reply
 

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