Accepted solution in C#


  • 1
    D
    public class Solution 
    {
        public void Rotate(int[] nums, int k) 
        {
            k %= nums.Length;
            if (k <= 0 || k == nums.Length) return;
            
            Reverse(nums, 0, nums.Length - 1);
            Reverse(nums, 0, k - 1);
            Reverse(nums, k, nums.Length - 1);
        }
        
        private void Reverse(int[] nums, int lower, int upper)
        {
            int count = (upper - lower) / 2;
            
            for (int i = 0; i <= count; i++)
            {
                int temp = nums[i + lower];
                nums[i + lower] = nums[upper - i];
                nums[upper - i] = temp;
            }
        }
    }
    

    Explanation:

    1. Get remainder of k / nums.Length to account for cases where k is larger than nums.Length.

    2. Return if k is equal to either zero or the length of nums because the rotated array will be unchanged from the original.

    3. Reverse entire array.

    4. Reverse array from element 0 up to k - 1.

    5. Reverse array from element k to nums.Length - 1;


Log in to reply
 

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