Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- class Solution {
- public int[] solution(int[] A, int K) {
- // If we got an empty array, just return it
- if (A.Length == 0) {
- return A;
- }
- // Set that allows us to track which indexes we rotated already
- var rotatedIndexes = new HashSet<int>();
- // We start from the first index
- int currentIndex = 0;
- // We get the value at the current index
- int currentValue = A[currentIndex];;
- // Number of rotations is the number of elements in A
- for (int r = 0; r < A.Length; r++) {
- // If the index was already rotated
- while (rotatedIndexes.Contains(currentIndex)) {
- // Go to the next index
- currentIndex++;
- // If we are past the length, get the correct one [index % length is a value ranging from 0 to length-1 (a valid index)]
- currentIndex %= A.Length;
- // Update the value to move to the current index
- currentValue = A[currentIndex];
- }
- // Calculate the next index
- int nextIndex = currentIndex + K;
- // Check again if we are past the length and calculate the corret index in case we do
- nextIndex %= A.Length;
- // Set temp value
- int tempValue = A[nextIndex];
- // Swap
- A[nextIndex] = currentValue;
- // Set next value
- currentValue = tempValue;
- // Add current index to rotated
- rotatedIndexes.Add(currentIndex);
- // Set the current index
- currentIndex = nextIndex;
- }
- return A;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement