문제
Remove Duplicates from Sorted Array 2
Remove Duplicates from Sorted Array II - LeetCode
Can you solve this real interview question? Remove Duplicates from Sorted Array II - Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place [https://en.wikipedia.org/wiki/In-place_algorithm] such that each unique elemen
leetcode.com
풀이
26. Remove Duplicates from Sorted Array 문제에서는 유니크한 요소 1개까지만 허용해줬었는데, 이번 문제에서는 최대 2개까지 허용해주는 문제이다.
그러므로 이전 코드에서는 바로 이전 요소와 현재 요소만 비교하면서 포인터를 옮겼다면, 이번 문제에서는 현재 포인터와 현재 포인터에서 -2를 한 위치의 요소와 비교를 하면 된다.
왜냐하면, 바로 이전 요소는 같던 다르던 상관없기 때문이다.
def removeDuplicates(nums):
if len(nums) <= 2:
return len(nums)
currentIndex = 2
for i in range(2, len(nums)):
if nums[i] != nums[currentIndex - 2]:
nums[currentIndex] = nums[i]
currentIndex += 1
return currentIndex
- 예외 상황으로 배열의 길이가 2이하인 배열은 그대로 반환해주면 예외 상황을 쉽게 해결해줄 수 있다.
'Leetcode' 카테고리의 다른 글
[Leetcode]_121. Best Time to Buy and Sell Stock (0) | 2023.09.21 |
---|---|
[Leetcode]_169. Majority Element (0) | 2023.09.18 |
[Leetcode]_26. Remove Duplicates from Sorted Array (0) | 2023.09.14 |
[Leetcode]_27. Remove Element (0) | 2023.09.13 |
[Leetcode]_88. Merge Sorted Array (Two Pointer) (0) | 2023.09.13 |