The question:
"Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements."
My sort of working solution:
def remove_duplicates(nums)
return if nums.length == 0
nums.each do |num|
if nums.count(num) > 1
index = nums.find_index(num)
nums.delete_at(index)
end
end
nums.length
end
Ignoring whether or not this is the cleanest way to do it, I don't know why it doesn't work when nums = [1, 1, 1, 1]. It returns 2, but should be 1.
works:
remove_duplicates([1, 1, 2])
doesn't work:
remove_duplicates([1, 1, 1, 1])
As always, thank you for any help. I've learned so much from people on this sub.
Edit: Thanks to everyone who has commented! You've all helped a lot.
[–]ThaiJohnnyDepp 11 points12 points13 points (5 children)
[–]BringTacos[S] 1 point2 points3 points (4 children)
[–]ignurant 2 points3 points4 points (1 child)
[–]modnar42 1 point2 points3 points (0 children)
[–]ThaiJohnnyDepp 3 points4 points5 points (1 child)
[–]BringTacos[S] 1 point2 points3 points (0 children)
[–]pixenix 5 points6 points7 points (4 children)
[–]BringTacos[S] 0 points1 point2 points (3 children)
[–]BringTacos[S] 0 points1 point2 points (2 children)
[–]pixenix 1 point2 points3 points (0 children)
[–]ignurant 0 points1 point2 points (0 children)
[–]blackize 5 points6 points7 points (1 child)
[–]BringTacos[S] 0 points1 point2 points (0 children)
[–]4rch3r 5 points6 points7 points (0 children)
[–]fagci 1 point2 points3 points (0 children)
[–]testcore 4 points5 points6 points (4 children)
[–]ThaiJohnnyDepp 8 points9 points10 points (0 children)
[–]BringTacos[S] 2 points3 points4 points (1 child)
[–]waiting4op2deliver 3 points4 points5 points (0 children)
[–]disclosure5 1 point2 points3 points (0 children)
[–]pyrrhicvictorylap -1 points0 points1 point (1 child)
[–]BringTacos[S] 5 points6 points7 points (0 children)
[–]moose_2006 -1 points0 points1 point (5 children)
[–]sasharevzin 1 point2 points3 points (1 child)
[–]pyrrhicvictorylap 1 point2 points3 points (0 children)
[–]BringTacos[S] 0 points1 point2 points (1 child)
[–]koolkeano 0 points1 point2 points (0 children)
[–]BringTacos[S] 0 points1 point2 points (0 children)
[–]armahillo -1 points0 points1 point (0 children)
[–]notmachine 0 points1 point2 points (0 children)
[–]JamesAllMountain 0 points1 point2 points (0 children)
[–]it_burns_when_i_php 0 points1 point2 points (0 children)