Array right rotation K times

By   Tewodros   Date Posted: Feb. 27, 2024  Hits: 452   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given a list of integers array we want to rotate the numbers to the right K times

Example

[1,2,3,4,5] k = 3

Ans:

[3,4,5,1,2]

Solution

This problem can be solved as follows. 

  1. Reverse the entire array.
  2. Reverse the first k elements of the array.
  3. Reverse the remaining elements of the array.

public class Solution {

   public void Rotate(int[] nums, int k) {

       if (nums == null || nums.Length <= 1 || k % nums.Length == 0) return;

       

       k %= nums.Length;

       

       Reverse(nums, 0, nums.Length - 1);

       Reverse(nums, 0, k - 1);

       Reverse(nums, k, nums.Length - 1);

   }

   

   private void Reverse(int[] nums, int start, int end) {

       while (start < end) {

           int temp = nums[start];

           nums[start] = nums[end];

           nums[end] = temp;

           start++;

           end--;

       }

   }

}

 


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* nvrsdc

Back to Top