mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
69 lines
1.4 KiB
Ruby
69 lines
1.4 KiB
Ruby
|
# @param {Integer[]} nums
|
||
|
# @param {Integer} k
|
||
|
# @return {Void} Do not return anything, modify nums in-place instead.
|
||
|
def rotate(nums, k)
|
||
|
def reverse(nums, from, to)
|
||
|
while from < to do
|
||
|
nums[from], nums[to] = nums[to], nums[from]
|
||
|
|
||
|
from += 1
|
||
|
to -= 1
|
||
|
end
|
||
|
end
|
||
|
|
||
|
k = k % nums.size
|
||
|
reverse(nums, 0, nums.size - 1)
|
||
|
reverse(nums, 0, k - 1)
|
||
|
reverse(nums, k, nums.size - 1)
|
||
|
end
|
||
|
|
||
|
RSpec.describe "rotate" do
|
||
|
it "nums = [1,2,3,4,5,6,7], k = 0" do
|
||
|
nums = [1,2,3,4,5,6,7]
|
||
|
k = 0
|
||
|
|
||
|
rotate(nums, k)
|
||
|
expect(nums).to eq([1,2,3,4,5,6,7])
|
||
|
end
|
||
|
|
||
|
it "nums = [1,2,3,4,5,6,7], k = 1" do
|
||
|
nums = [1,2,3,4,5,6,7]
|
||
|
k = 1
|
||
|
|
||
|
rotate(nums, k)
|
||
|
expect(nums).to eq([7,1,2,3,4,5,6])
|
||
|
end
|
||
|
|
||
|
it "nums = [1,2,3,4,5,6,7], k = 2" do
|
||
|
nums = [1,2,3,4,5,6,7]
|
||
|
k = 2
|
||
|
|
||
|
rotate(nums, k)
|
||
|
expect(nums).to eq([6,7,1,2,3,4,5])
|
||
|
end
|
||
|
|
||
|
it "nums = [1,2,3,4,5,6,7], k = 3" do
|
||
|
nums = [1,2,3,4,5,6,7]
|
||
|
k = 3
|
||
|
|
||
|
rotate(nums, k)
|
||
|
expect(nums).to eq([5,6,7,1,2,3,4])
|
||
|
end
|
||
|
|
||
|
it "nums = [-1,-100,3,99], k = 1" do
|
||
|
nums = [-1,-100,3,99]
|
||
|
k = 1
|
||
|
|
||
|
rotate(nums, k)
|
||
|
expect(nums).to eq([99,-1,-100,3])
|
||
|
end
|
||
|
|
||
|
it "nums = [-1,-100,3,99], k = 2" do
|
||
|
nums = [-1,-100,3,99]
|
||
|
k = 2
|
||
|
|
||
|
rotate(nums, k)
|
||
|
expect(nums).to eq([3,99,-1,-100])
|
||
|
end
|
||
|
end
|