본문 바로가기

문돌이 존버/프로그래밍 스터디

(leetcode 문제 풀이) 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.

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.

Custom Judge:
The judge will test your solution with the following code:
If all assertions pass, then your solution will be accepted.
 
Example 1:
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).

Example 2:
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
2. -100 <= nums[i] <= 100
3. nums is sorted in non-decreasing order.
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        i = 0
        for j in range(1, len(nums)):
            if nums[i] != nums[j]:
                i += 1
                nums[i] = nums[j]
        
        return i + 1

가장 주의해야 할 점은 또 다른 어레이를 위해 새로운 메모리 공간을 사용하지 말라는 것이다. 단순하게 중복 문제를 해결하는 것은 set() 함수를 사용하는 것인데, 이는 문제 조건에 위배되기 때문에 어떻게 풀어야 할지 고민했다.

그러다 참고한 것이 투 포인터 알고리즘이었다. 이미 주어진 nums는 오름차순으로 정렬되어 있고, 우리는 중복되지 않은 숫자 갯수만 파악하면 된다. 다만 일반적인 투 포인터처럼 첫 원소와 마지막 원소에서 시작하는 것이 아니라 모두 왼쪽부터 시작한다.

j를 정찰병으로 하고 j번째 원소와 다르면 i 위치를 한 칸씩 오른쪽으로 옮기고 i번째 원소를 j번째 원소로 대체하면 된다. 아래 그림을 참고하면 이해가 쉬울 것이다.

위 과정을 계속 반복하면 어느 순간 i가 움직이지 않을 때(=숫자가 계속 중복될 때)가 올 것이며, 이때 i의 위치에 1을 더한 값이 k가 된다(i는 0부터 시작했기 때문에).

728x90
반응형