mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-27 21:58:57 +01:00
Remove Element: two pointers approach
This commit is contained in:
parent
780c324417
commit
ad35c2398c
1 changed files with 27 additions and 2 deletions
|
@ -1,7 +1,7 @@
|
||||||
# Arrays - Remove Elements
|
# Arrays - Remove Elements
|
||||||
#
|
#
|
||||||
# Given an array nums and a value val, remove all instances of that value in-place and return the new length.
|
# Given an array nums and a value val, remove all instances of that value in-place and return the new length.
|
||||||
# Do not allocate extra space for another array,
|
# Do not allocate extra space for another array,
|
||||||
# you must do this by modifying the input array in-place with O(1) extra memory.
|
# you must do this by modifying the input array in-place with O(1) extra memory.
|
||||||
# The order of elements can be changed. It doesn't matter what you leave beyond the new length.
|
# The order of elements can be changed. It doesn't matter what you leave beyond the new length.
|
||||||
#
|
#
|
||||||
|
@ -37,7 +37,7 @@ def remove_elements(nums, val)
|
||||||
result_length = nums.length
|
result_length = nums.length
|
||||||
shift_length = 0
|
shift_length = 0
|
||||||
nums.each_with_index do |num, i|
|
nums.each_with_index do |num, i|
|
||||||
if num == val
|
if num == val
|
||||||
nums.delete_at(i)
|
nums.delete_at(i)
|
||||||
nums.unshift('removed')
|
nums.unshift('removed')
|
||||||
result_length -=1
|
result_length -=1
|
||||||
|
@ -52,3 +52,28 @@ puts remove_elements([3,2,2,3], 3)
|
||||||
# => 2
|
# => 2
|
||||||
puts remove_elements([0,1,2,2,3,0,4,2], 2)
|
puts remove_elements([0,1,2,2,3,0,4,2], 2)
|
||||||
# => 5
|
# => 5
|
||||||
|
|
||||||
|
#
|
||||||
|
# Approach 3: Two-pointer
|
||||||
|
#
|
||||||
|
|
||||||
|
def remove_element(nums, val)
|
||||||
|
pointer1 = 0
|
||||||
|
pointer2 = nums.length
|
||||||
|
|
||||||
|
while pointer1 < pointer2
|
||||||
|
if nums[pointer1] == val
|
||||||
|
nums[pointer1] = nums[pointer2 - 1]
|
||||||
|
pointer2 -= 1
|
||||||
|
else
|
||||||
|
pointer1 += 1
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
pointer1
|
||||||
|
end
|
||||||
|
|
||||||
|
puts remove_elements([3,2,2,3], 3)
|
||||||
|
# => 2
|
||||||
|
puts remove_elements([0,1,2,2,3,0,4,2], 2)
|
||||||
|
# => 5
|
||||||
|
|
Loading…
Reference in a new issue