Share my AC Java Solution


  • 0
    S

    For example
    1 2 3 4 5 6 7 /// k = 4
    First reverse all -> 7 6 5 4 3 2 1
    Then we reverse first k Numbers -> 4 5 6 7 | 3 2 1
    Last, we reverse the rest numbers -> 4 5 6 7 | 1 2 3

    public class Solution {
        public void rotate(int[] nums, int k) {
            k = k % nums.length;
            if(k==0) return;
            reverse(nums, 0, nums.length-1);
            reverse(nums, 0, k-1);
            reverse(nums, k, nums.length-1);
        }
        public static void reverse(int[] nums, int left, int right) {
            while(left < right) {
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
                left++;
                right--;
            }
        }
    }
    

Log in to reply
 

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