정수 목록에서 중복 제거하기 (쉬움) | LeetCode Practice # 7

작성자

카테고리:

← 피드로
DEV Community · 睡觉 · 2026-07-19 개발(SW)

睡觉

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

Enter fullscreen mode Exit fullscreen mode

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.

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다