본문 바로가기

Algorithm/Leetcode

[Top Interview 150 - Array / String] 26. Remove Duplicates from Sorted Array

[Q] [Easy]

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. 
Then return the number of unique elements in nums.

Consider the number of unique elements of nums to be k, 
to get accepted, you need to do the following things:

Change the array nums such that the first k elements of nums contain 
the unique elements in the order they were present in nums initially. 
The remaining elements of nums are not important as well as the size of nums.
Return k.

 

  • 리스트 중복 문제는 생각할 것도 없이 set() 문제였는데, leetcode 는 in-place 문제가 많기 때문에 조심해야한다.
  • 아래 코드를 작성하는데 "cnt -= 1" 을 생각 못해서 조금 헤맸다. 왜이렇게 바보일까
  • 만약 해당 cnt 번째 수가 중복이라서 제거가 되었다면 Index 가 하나 줄었기 때문에 하나 삭제 해줘야한다!!!
# Answer

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """

        init_len = len(nums)

        # remove duplicates in-place
        cnt = 1
        for _ in range(1, init_len):
            if nums[cnt] in nums[:cnt]:
                del nums[cnt]
                cnt -= 1
            cnt += 1

        # k
        k = len(nums)

        # [] -> + _
        n = init_len - k
        nums += '_' * n


        return k