C# - rotate forward solution (key is do/while)


  • 1
    public void Rotate(int[] nums, int k) {
        if (k == 0) return;
        int len = nums.Length;
        int count = 0;
        int start = 0;
        
        while (count < len)
        {
            int i = start;
            int prev = nums[(((i - k) % len) + len) % len];
            do
            {
                int temp = nums[i];
                nums[i] = prev;
                prev = temp;
                i = (i + k) % len;
                count++;
            }
            while (i != start);
            start++;
        }
    }

Log in to reply
 

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