1 분 소요

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.
Return k after placing the final result in the first k slots of nums.
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

하나의 리스트(nums1)가 주어진다.
리턴 값 없이, nums1에서 중복값을 제거한 뒤에 오름차순 정렬하는 문제였다.

Example

Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -100 <= nums[i] <= 100
  • nums is sorted in non-decreasing order.

Solution

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        res=set() # 중복을 제거하는 자료구조 set (중복된 값을 넣으면 한번만 들어감)
        for x in nums:
            res.add(x) # set 자료구조는 add()로 요소 추가
        res=list(res) # set -> list
        
        nums.clear()
        for x in res:
            nums.append(x)
        nums.sort()
  • 직접 푼 풀이이다.
  • set 자료구조를 활용하면 쉽게 풀 수 있다.
  • set 자료구조는 sort 기능이 없어 나중에 리스트로 변경해야한다.

끄적

  • 영어로 적혀 있어서 문제를 해석하는 것 보다 빠르게 예제를 확인하는게 나았다.


💛 개인 공부 기록용 블로그입니다. 👻

맨 위로 이동하기