The official Leetcode page talks about four following approaches:
- Approach 1: Brute Force
- Approach 2: Using Extra Array
- Approach 3: Using Cyclic Replacements
- Approach 4: Using Reverse
The second approach can be done like this: (but only works in irb and not on leetcode somehow)
# @param {Integer[]} nums
# @param {Integer} k
# @return {Void} Do not return anything, modify nums in-place instead.
def rotate(nums, k)
return nums if k == 0
k = k % nums.size
ans = Array.new(nums.size, 0)
(nums.size).times do |i|
ans[(i + k) % nums.size] = nums[i]
end
ans
end
The forth approach can be done like this:
# @param {Integer[]} nums
# @param {Integer} k
# @return {Void} Do not return anything, modify nums in-place instead.
def rotate(nums, k)
return nums if k == 0
k = k % nums.size
def reverse_elements(array, left_idx, right_idx)
while left_idx < right_idx
array[left_idx], array[right_idx] = array[right_idx], array[left_idx]
left_idx += 1
right_idx -= 1
end
end
reverse_elements(nums, 0, nums.size - 1) # this line is much faster than using nums.reverse!
reverse_elements(nums, k, nums.size - 1)
reverse_elements(nums, 0, k - 1)
nums
end
One of my solutions that worked for me is:
# @param {Integer[]} nums
# @param {Integer} k
# @return {Void} Do not return anything, modify nums in-place instead.
def rotate(nums, k)
return nums if k == 0
k = k % nums.size
popped = nums.slice!(-k..-1)
nums.unshift(*popped)
end
Another solution which worked in irb, but failed on leetcode:
# @param {Integer[]} nums
# @param {Integer} k
# @return {Void} Do not return anything, modify nums in-place instead.
def rotate(nums, k)
return nums if k == 0
k = k % nums.size
ans = []
ans.insert(0, *nums[-k..-1])
ans.insert(k, *nums[0..(-k - 1)])
ans
end