문제 링크 : https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
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.
nums: an integer array
- <= nums.length <=
- - <= nums[i] <=
- nums is sorted in non-decreasing order.
: cur, k를 이용한다.
반복문으로 첫번째 원소를 제외하고 순회하는데,
이전에 있는 원소와 같으면 지나가고
다른 원소가 나오면 cur을 현재 원소로 바꾸고,
nums[k]에 지금 수를 저장하고, k에 1을 더한다.
배열이 없는 경우에는 반복문을 순회할 수 없으므로 0을 return한다.
시간 복잡도 : O(N)
공간 복잡도 : O(1)
def removeDuplicates(nums: list[int]) -> int:
if len(nums) <= 0:
return 0
cur, k = nums[0], 1
for i in range(1, len(nums)):
if cur != nums[i]:
cur = nums[i]
nums[k] = cur
k = k + 1
return k
- []
- [1,2,3,4]
- [1,1,2]
- [1,1,2,2,3]
: 빈 배열, 겹치지 않는 경우, 한 번 겹치는 경우, 여러 번 겹치는 경우
모두 통과했다.

별로 어렵지 않은 문제라서 쉽게 풀 수 있었다.

아주 쉽게 이해할 수 있었다.
하마터면 빈 배열을 놓치고 넘어갈 뻔 했다.
다음부터 주의하도록 하자