standard jdk with less step movements


  • 0
    X
    public void rotate(int[] nums, int k) {
        if (nums == null || nums.length <= 1 || k % nums.length == 0) {
            return;
        }
    
        final int len = nums.length;
        k = k % len;
    
        for (int cycleStart = 0, nMoved = 0; nMoved < len; cycleStart++) {
            int tmp = nums[cycleStart];
            int curr = cycleStart;
            int next = curr < k ? curr - k + len : curr - k;
            
            while (next != cycleStart) {
                nums[curr] = nums[next];
                curr = next;
                next = curr < k ? curr - k + len : curr - k;
    
                nMoved++;
            }
    
            nums[curr] = tmp;
            nMoved++;
        }
    }
    

Log in to reply
 

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