[LeetCode] 26. Remove Duplicates from Sorted Array

조수훈·2023년 8월 24일

Algorithm

목록 보기
5/5
post-thumbnail

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.
Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length

int k = removeDuplicates(nums); // Calls your implementation

assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}
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).

문제링크 : https://leetcode.com/problems/remove-duplicates-from-sorted-array/?envType=study-plan-v2&envId=top-interview-150

Solution

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        stack = []
        stack.append(nums[0])
        for item in nums[1:]:
            if item != stack[-1]:
                stack.append(item)
        
        for i in range(len(stack)):
            nums[i]=stack[i]

        return len(stack)

단순히 stack 을 활용한 풀이이다. 겹치지 않는 숫자를 stack 에 넣고 다시 nums 에 옮겨준다.

하지만 이 풀이는 불필요한 메모리 stack 배열을 사용하므로, 조금더 좋은 방식이 있는지 생각해보았다.

Develop

###틀린풀이!!###
   def removeDuplicates(self, nums: List[int]) -> int:

        left = 0
        right = 0
        cur = 0
        while(left < len(nums)):
            if left == len(nums)-1:
                nums[cur] =nums[-1]
                break
            if nums[left] != nums[right]:
                nums[cur]= nums[left]
                cur +=1
                left = right
            elif nums[left] == nums[right]:
                right +=1
            
        return cur+1

two pointer를 활용하여 , nums[left] 와 nums[right]가 같아질때마다 left 포인터와 right 포인터를 같게하였다. 테스트 케이스는 통과했지만, 종료조건이 맞지않았는지 실패로 나왔다..
포인터 두개가 대입이 되어버리면 종료조건을 잘 생각하기가 어려운거같다...

다음 코드는 cur 을 없애고 , 포인터 두개의 대입과정을 없앤 코드이다.

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        left = 0
        right = 1
        
        while left <= right and right < len(nums):
            if nums[left] == nums[right]:
                right +=1
            else:
                nums[left+1] = nums[right]
                left +=1
            
        
        return left +1 

stack 배열을 없애 공간복잡도를 개선하였다.

다음 코드는 다른사람의 풀이이다.

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        cur = 1
        for i in range(1, len(nums)):
            if nums[i] != nums[i - 1]:
                nums[cur] = nums[i]
                cur += 1
        return cur

현재위치를 cur 로 놓고, for 문을 nums의 크기만큼 돈다.
for 문을 돌면서 nums[i] 가 nums[i-1] 랑 다르다면 현재위치에 그 nums[i] 를 대입히고, 현재위치를 +1한다.

profile
잊지 않기 위해 기록하기

0개의 댓글