mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-27 21:58:57 +01:00
Add two pointers approach
This commit is contained in:
parent
a8f816f984
commit
ad685ac4ee
1 changed files with 45 additions and 12 deletions
|
@ -34,18 +34,18 @@ def shuffle(nums, n)
|
||||||
result
|
result
|
||||||
end
|
end
|
||||||
|
|
||||||
# nums = [2, 5, 1, 3, 4, 7]
|
nums = [2, 5, 1, 3, 4, 7]
|
||||||
# n = 3
|
n = 3
|
||||||
# print(shuffle(nums, n))
|
print(shuffle(nums, n))
|
||||||
# # Output: [2,3,5,4,1,7]
|
# Output: [2,3,5,4,1,7]
|
||||||
# nums = [1, 2, 3, 4, 4, 3, 2, 1]
|
nums = [1, 2, 3, 4, 4, 3, 2, 1]
|
||||||
# n = 4
|
n = 4
|
||||||
# print(shuffle(nums, n))
|
print(shuffle(nums, n))
|
||||||
# # Output: [1,4,2,3,3,2,4,1]
|
# Output: [1,4,2,3,3,2,4,1]
|
||||||
# nums = [1, 1, 2, 2]
|
nums = [1, 1, 2, 2]
|
||||||
# n = 2
|
n = 2
|
||||||
# print(shuffle(nums, n))
|
print(shuffle(nums, n))
|
||||||
# # Output: [1,2,1,2]
|
# Output: [1,2,1,2]
|
||||||
|
|
||||||
#
|
#
|
||||||
# Approach 2: Use Ruby methods .insert() and .delete_at()
|
# Approach 2: Use Ruby methods .insert() and .delete_at()
|
||||||
|
@ -74,3 +74,36 @@ nums = [1, 1, 2, 2]
|
||||||
n = 2
|
n = 2
|
||||||
print(shuffle(nums, n))
|
print(shuffle(nums, n))
|
||||||
# Output: [1,2,1,2]
|
# Output: [1,2,1,2]
|
||||||
|
|
||||||
|
#
|
||||||
|
# Approach 3: Two Pointers
|
||||||
|
#
|
||||||
|
# Time Complexity: O(N)
|
||||||
|
#
|
||||||
|
|
||||||
|
def shuffle(nums, n)
|
||||||
|
result = []
|
||||||
|
p1 = 0
|
||||||
|
p2 = n
|
||||||
|
|
||||||
|
while p1 < n
|
||||||
|
result.push(nums[p1], nums[p2])
|
||||||
|
p1 +=1
|
||||||
|
p2 +=1
|
||||||
|
end
|
||||||
|
|
||||||
|
result
|
||||||
|
end
|
||||||
|
|
||||||
|
nums = [2, 5, 1, 3, 4, 7]
|
||||||
|
n = 3
|
||||||
|
print(shuffle(nums, n))
|
||||||
|
# Output: [2,3,5,4,1,7]
|
||||||
|
nums = [1, 2, 3, 4, 4, 3, 2, 1]
|
||||||
|
n = 4
|
||||||
|
print(shuffle(nums, n))
|
||||||
|
# Output: [1,4,2,3,3,2,4,1]
|
||||||
|
nums = [1, 1, 2, 2]
|
||||||
|
n = 2
|
||||||
|
print(shuffle(nums, n))
|
||||||
|
# Output: [1,2,1,2]
|
Loading…
Reference in a new issue