-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge2SortedArray.py
60 lines (42 loc) · 1.4 KB
/
merge2SortedArray.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from typing import List
class Solution:
def reverse(self, nums: List[int], start: int, end: int) -> None:
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
def rotate(self, nums: List[int], k: int) -> None:
n = len(nums)
k %= n # Handle the case where k >= n
self.reverse(nums, 0, n - 1) # Reverse the entire array
self.reverse(nums, 0, k - 1) # Reverse the first k elements
self.reverse(nums, k, n - 1) # Reverse the remaining n - k elements
# Example usage:
solution = Solution()
nums = [1, 2, 3, 4, 5, 6, 7]
k = 3
solution.rotate(nums, k)
print(nums) # Output: [5, 6, 7, 1, 2, 3, 4]
def rotate(nums,k):
n = len(nums)
k = k % n
for i in range(k):
previous = nums[n-1]
# n -= 1
for j in range(len(nums)):
nums[j], previous = previous, nums[j]
return nums
print(rotate([1,2,3,4], 2))
# SOLUTION METHOD 3 ---- Using Extra Space
def rotate(nums, k):
n = len(nums)
k = k % n # Handle the case where k >= n
rotated = [0] * n
for i in range(n):
rotated[(i + k) % n] = nums[i]
nums[:] = rotated # Copy the rotated array back to nums
# Example usage:
nums = [1, 2, 3, 4, 5, 6, 7]
k = 3
rotate(nums, k)
print(nums) # Output: [5, 6, 7, 1, 2, 3, 4]