C# Easy to read


  • 0
    X

    Here is my thinking process.

    Since we need to move k elements to the right, that means k elements from the end of the array will be replaced by previous elements in the array.

    For example, if we have [1,2,3,4,5,6,7], k = 1 means 7 will be replaced, k = 2 means 6 and 7 will be replaced, k = 3 means 5, 6, 7 will be replaced.

    As a result, we need to save these numbers before we start shifting the rest of the array elements to the right.

    Then we simply replace the first k elements in the array with the ones we saved.

        public void Rotate(int[] nums, int k) {
                if (k == 0 || nums == null || nums.Length < 2)
                {
                    return;
                }
    
                // takes care of overflow
                k = k % nums.Length;
    
                int[] temp = new int[k];
    
                // Save k elements from the end of the array
                for (int i = 0; i < k; i++)
                {
                    temp[i] = nums[nums.Length - k + i];
                }
    
                // Shift all elements k positions to the right starting from the end of the array
                for (int i = nums.Length - 1; i > k - 1; i--)
                {
                    nums[i] = nums[i - k];
                }
    
                // Copy those saved elements back to the front of the array
                for (int i = 0; i < temp.Length; i++)
                {
                    nums[i] = temp[i];
                }
    
                return;
        }
    

    This would be O(k % nums.Length) space and O(n) time.


Log in to reply
 

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