Leetcode
[Leetcode]_26. Remove Duplicates from Sorted Array
Wix
2023. 9. 14. 18:54
문제
Remove Duplicates from Sorted Array
Remove Duplicates from Sorted Array - LeetCode
Can you solve this real interview question? Remove Duplicates from Sorted Array - Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place [https://en.wikipedia.org/wiki/In-place_algorithm] such that each unique element ap
leetcode.com
풀이
오름차순으로 정렬된 배열이 주어지고 해당 배열을 앞에서부터 유니크한 요소로만 재배치하고 마지막에는 유니크한 요소의 갯수를 반환하는 문제이다.
오름차순으로 정렬되었기때문에 인덱스로 순회하면서 이전 요소와 현재 요소가 다르면 유니크한 요소 갯수를 추가한다.
그리고 유니크한 요소를 추가하기 이전의 해당 갯수는 이전 요소의 인덱스와도 일치한다.
앞에서부터 유니크한 요소들로 재배치해야하기 때문에, 이전 요소에 인덱스에 현재 요소로 수정한다.
def removeDuplicates(nums):
curr = nums[0]
pointer = 1
for num in nums:
if curr != num:
curr = num
nums[pointer] = num
pointer += 1
return pointer