O(1) space Java solution


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

    }


  • 6
    L

    Why don't you do k=k%n instead of the first seven lines?


  • 0
    W

    thanks for the help!

    I used this for start; might help someone else.

    int start = (k + nums.length) % nums.length;


Log in to reply
 

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