Java code simple reverse


  • 0
    Y
    public class Solution {
        public void rotate(int[] nums, int k) {
            if(nums.length <= 1) {
                return;
            }
            k = k % nums.length;
            int mid = nums.length - k;
            reverse(nums, mid, nums.length - 1);
            reverse(nums, 0, mid - 1);
            reverse(nums, 0, nums.length - 1);
        }
        
        private void reverse(int[] nums, int start, int end) {
            while(start < end) {
                nums[start] = nums[start] ^ nums[end];
                nums[end] = nums[start] ^ nums[end];
                nums[start] = nums[start] ^ nums[end];
                start++;
                end--;
            }
        }
    }

Log in to reply
 

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