Java (1ms) simple O(n) time and O(1) space


  • 0
    P
        public void rotate(int[] nums, int k) {
            int n = nums.length;
            if (k <= 0)
                return;
            k = k % n;
            revert(nums, 0, n);
            revert(nums, 0, k);
            revert(nums, k, n);
        }
        
        private void revert(int[] nums, int start, int end) {
            int mid = start + (end - start) / 2;
            for (int i = start, j = end - 1; i < mid; i++, j--) {
                int t = nums[i];
                nums[i] = nums[j];
                nums[j] = t;
            }
        }
    

Log in to reply
 

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