[코딩테스트] 80. Remove Duplicates from Sorted Array II Python

주먹밥밥·2024년 2월 13일

문제💡

Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. 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.

Example 1

입력: nums = [1,1,1,2,2,3]
출력: 5, nums = [1,1,2,2,3,_]
설명: 함수는 k = 5를 반환해야 하며, nums 배열의 처음 다섯 요소는 각각 1, 1, 2, 2, 3이어야 합니다.

Example 2

입력: nums = [0,0,1,1,1,1,2,3,3]
출력: 7, nums = [0,0,1,1,2,3,3,,]
설명: 함수는 k = 7을 반환해야 하며, nums 배열의 처음 일곱 요소는 각각 0, 0, 1, 1, 2, 3, 3이어야 합니다.

문제 해석✏️

정수 배열 nums에서 일부 중복을 제거하는 것과 관련이 있습니다. 각 고유한 요소가 최대 두 번씩 나타나도록 중복을 제거

문제

1. 포인터 2개가 같은 방향으로 진행해 나아가는 것
2. 포인터 2개가 양끝에서 반대로 진행되는 것
3. 포인터 하나는 한 쪽 방향으로만 진행하고, 다른 포인터는 양쪽으로 이동하는 것

# 중복은 최대 2개까지만 나오게 하기
# two pointers
from typing import List
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if len(nums) == 0:
            return 0
        
        i = 1 # 첫 요소와 두 번째 요소는 검사할 필요가 없으니끼 (첫번쩨 , 두번째 그대로 유지)
        for j in range(2,len(nums)): # 중복이 최대 2개를 넘지 않는다.
            if nums[j] != nums[i-1]:#j 와 i-1 인수가 다르면
                i+=1 #i에 1을 더하고 
                nums[i] = nums[j] # 그 더한 값이랑 j 값이랑 같아야함
        return i+1
profile
코딩은 열심히 해야겠지...?

0개의 댓글