mirror of
https://github.com/TheAlgorithms/Ruby
synced 2025-01-15 03:43:22 +01:00
Add another approach
This commit is contained in:
parent
d5877acb14
commit
9576b18a61
1 changed files with 25 additions and 0 deletions
|
@ -57,6 +57,31 @@ puts remove_elements([0,1,2,2,3,0,4,2], 2)
|
||||||
# Approach 3: Two-pointers
|
# Approach 3: Two-pointers
|
||||||
#
|
#
|
||||||
|
|
||||||
|
# Complexity analysis
|
||||||
|
#
|
||||||
|
# Time complexity: O(n).
|
||||||
|
# Assume the array has a total of n elements,
|
||||||
|
# both i and j traverse at most 2n steps.
|
||||||
|
#
|
||||||
|
# Space complexity: O(1).
|
||||||
|
|
||||||
|
def remove_element(nums, val)
|
||||||
|
pointer1 = 0
|
||||||
|
|
||||||
|
nums.each_with_index do |num, pointer2|
|
||||||
|
if val != num
|
||||||
|
nums[pointer1] = nums[pointer2]
|
||||||
|
pointer1 += 1
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
pointer1
|
||||||
|
end
|
||||||
|
|
||||||
|
#
|
||||||
|
# Approach 4: Two-pointers (Optimized)
|
||||||
|
#
|
||||||
|
|
||||||
# Complexity analysis
|
# Complexity analysis
|
||||||
#
|
#
|
||||||
# Time complexity: O(n). Both i and n traverse at most n steps.
|
# Time complexity: O(n). Both i and n traverse at most n steps.
|
||||||
|
|
Loading…
Reference in a new issue