Created
January 31, 2022 14:21
-
-
Save tanmay27vats/44ed0e9f3e3ad2984db0f07568423176 to your computer and use it in GitHub Desktop.
[Ruby] Rotate Array - Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Example 2: Input: nums…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# @param {Integer[]} nums | |
# @param {Integer} k | |
# @return {Void} Do not return anything, modify nums in-place instead. | |
def rotate(nums, k) | |
count = 0 | |
start = 0 | |
while (count < nums.size) | |
current = start | |
prev = nums[start] | |
loop do | |
next_index = (current + k) % nums.size; | |
temp = nums[next_index] | |
nums[next_index] = prev | |
prev = temp; | |
current = next_index | |
count += 1 | |
break if start == current | |
end | |
start += 1 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment