Remove Duplicates From Sorted Array
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. Consider the number of unique elements in nums to be k. After removing duplicates, return the number of unique elements k.
The first k elements of nums should contain the unique numbers in sorted order. The remaining elements beyond index k - 1 can be ignored.
Python
####Pop Elements(Runtime: 57ms, Memory: 13MB)
#DECLARE nums: ARRAY of INTEGER
class Solution(object):
def removeDuplicates(self, nums):
i = 1
while i < len(nums):
if nums[i] == nums[i-1]:
nums.pop(i)
else:
i += 1
return len(nums)
####Insert to Head(Runtime: 7ms, Memory: 13.7MB)
#DECLARE nums: ARRAY of INTEGER
class Solution(object):
def removeDuplicates(self, nums):
head_pointer = 1
for i in range(1, len(nums)):
if nums[i] != nums[i-1]:
nums[head_pointer] = nums[i]
head_pointer += 1
return head_pointer
Thoughts
The question is simple. The only catch: we need to accept that the array can become messy, because after moving the unique elements to the front, anything after index k will be unorganized. However, since the question already states that "anything beyond index k-1 will not be considered", I think LeetCode is hinting at this approach.
Top comments (0)