본문 바로가기

leetcode

[leetcode] 26. Remove Duplicates from Sorted Array

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        ans = 0
        nums_new = sorted(set(nums))
        for i, v in enumerate(nums_new):
            ans = ans + 1
            nums[i] = v
            
        del nums[ans:]
        return ans

[문제]

정렬된 배열이 input으로 들어오고, 중복된 숫자를 제거해서 전체 갯수를 리턴한다.

단, nums도 직접 수정을 해야 한다. 아래와 같이 사용하기 위해서

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

[풀이]

파이썬이 역시 좋긴 좋다.

리스트 -> Set으로 해서 중복 제거 -> sorted 사용해서 정렬 -> 기존 리스트에 대입

del nums[ans:]를 통해서 필요 없는 뒷 부분 리스트 요소들은 제거