記錄下自己拙計的算法之旅
**LeetCode
Rotate Array:**
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
語言 ruby
def rotate(nums, k)
num_cp = nums.clone
pos = k % nums.length
start_pos =
nums.length.times do
nums[pos] = num_cp[start_pos]
start_pos +=
pos +=
pos %= nums.length
end
end
空間複雜度為O(n),時間複雜度O(n),拙計~~
另一種方法
def rotate2 nums, k
nums_length = nums.length
k = k % nums_length
return if k == || nums_length ==
k.times do
temp = nums[nums_length-]
point = nums_length-
point.times do
nums[point] = nums[point-]
point -=
end
nums[] = temp
end
end
但是時間複雜度為O(n^2),空間為O(1),直接Time Limit Exceeded,更拙計 = =