[LeetCode] Top Interview 150 Problems Solving # 26 Remove Duplicates from Sorted Array
Understanding the Problem
A given list nums has numbers from -100 to 100 in an arranged order. The task is to change nums in place by finding duplicate numbers and removing them. nums should stay with unique numbers only. It is not important to return any value from the function as this problem only deals with nums.
Approach
Should I go with remove() method or replace()? remove() will cause an error in the loop so I decided to replace the duplicate numbers into something that could be marked as duplicate and removed later.
Solution
I wanted to keep the unique numbers somewhere as
temp, to use it for checking other numbers whether they are duplicate or not.I would go by
forloop while checking unique numbers. If the numbernums[i]is not unique and has been duplicate, I changed it with-1000.I sorted the number to have
-1000numbers to the starting of the index.Then I redeclared
numswith the slicednums, which sliced all-1000numbers.
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
temp = []
for i in range(len(nums)):
if nums[i] not in temp:
temp.append(nums[i])
else:
nums[i] = -1000
nums.sort()
count = nums.count(-1000)
nums[:] = nums[count:]
return
Reflection
Changing the number in place is a little bit tricky, and the methods may be not working the way I think it should. I guess it is only the matter of practice.
Another thing that I noticed on LeetCode is, that there is a lack of explanation so in some problems I myself need to find a way to break through the barriers towards the solution, interpreting what the actual instruction is and what to return. This problem too. It tells me to return the k which is the length of the unique numbers but it was nothing about the k. Well, I guess I will figure solution out myself and just go with it.
About the author
South Korean, master's degree of AI. A research focused AI specialist, and a rogrammer for LLM. I am seeking opportunities worldwide. I used to live in Frankfurt, Moscow, Pretoria, Baguio. Where to next?
Comments
Join the discussionNo comments yet. Be the first to comment.




