Same as reverse string


  • 0
    C
        public void rotate(int[] nums, int k) {
            if(nums.length == 0 || k < 1){
                return;
            }
            
            k = k%nums.length;
            
            reverse(nums, 0, nums.length - 1);        
            reverse(nums, 0, k-1);
            reverse(nums, k, nums.length - 1);
        }
        
        private void reverse(int[] nums, int beg, int end){
            while(beg < end){
                int temp = nums[beg];
                nums[beg++] = nums[end];
                nums[end--] = temp;
            }
        }
    

Log in to reply
 

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