diff --git a/data_structures/arrays/remove_elements.rb b/data_structures/arrays/remove_elements.rb index 32260ac..6176ba1 100644 --- a/data_structures/arrays/remove_elements.rb +++ b/data_structures/arrays/remove_elements.rb @@ -1,7 +1,7 @@ # Arrays - Remove Elements # # 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. # 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 shift_length = 0 nums.each_with_index do |num, i| - if num == val + if num == val nums.delete_at(i) nums.unshift('removed') result_length -=1 @@ -52,3 +52,28 @@ puts remove_elements([3,2,2,3], 3) # => 2 puts remove_elements([0,1,2,2,3,0,4,2], 2) # => 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