Java code O(n) time , O(1)space and 1ms without reverse


  • 0
    D
    public void rotate(int[] nums, int k) {
            if (nums == null || nums.length == 0 || (k %= nums.length) == 0) {
                return;
            }
            int n = nums[0];
            int currIndex = 0;
            int offsetCount = 0;
            for (int i = 0;i<nums.length;i++) {
                if (offsetCount % nums.length == 0) {
                    currIndex += 1;
                    n = nums[currIndex % nums.length];
                    offsetCount = 0;
                }
                int nextIndex = (currIndex + k) % nums.length;
                int temp = nums[nextIndex];
                nums[nextIndex] = n;
                n = temp;
                currIndex += k;
                offsetCount += k;
            }
        }
    

Log in to reply
 

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