무냐의 개발일지
26. Remove Duplicates from Sorted Array -_- 본문
👩💻 문제
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.
💡 풀이
def removeDuplicates(self, nums: List[int]) -> int:
k = 1
for i in range(1, len(nums)):
if nums[i] != nums[i-1]:
nums[k] = nums[i]
k += 1
return k
✍️ 해설
예시 ) [1, 1, 2, 3, 3, 4, 5] (길이 7, 인덱스 0,1,2,3,4,5,6)
결과 ) [1, 2, 3, 4, 5], k = 5 를 반환해야 한다
k = 1
이를 위해서
range(1, len(nums)) : range(1,7)
0,1,2,3,4,5,6 인덱스까지 순회를 돈다
nums[i] != nums[i-0] 일떄
1) [1, 1, 2, 3, 3, 4, 5], i =1, k= 1
1, 1 비교. 같음. 무시
2) [1, 1, 2, 3, 3, 4, 5] i =2, k=1
1, 2 비교. 다름. k=1인데, nums[k] = 1 이 있던 자리! nums[i] = 2 가 있다
nums[k] = nums[i] 해버리면, nums 는 [1, 2, 2, 3, 3, 4, 5] => 중복되는 1이 없어진다
k += 1 --> 2
3) [1, 2, 2, 3, 3, 4, 5], i=3, k=2
2, 3 비교. 다름. k=2, i는 3임
nums[2] (2) = nums[3] (3)
nums는 [1, 2, 3, 3, 3, 4, 5] 가 됨
k += 1 --> 3
4) [1, 2, 3, 3, 3, 4, 5] , i=4, k=3
3, 3 비교. 같음. 무시
5) [1, 2, 3, 3, 3, 4, 5], i= 5, k=3
3, 4 비교. 다름. k=3, i=5
num[3] = num[5]
[1, 2, 3, 4, 3, 4, 5]
k += 1 --> 4
6) [1, 2, 3, 4, 3, 4, 5], i=6, k= 4
4,5비교. 다름.
num[4] = num[6]
[1, 2, 3, 4, 5, 4, 5]
k += 1 --> 5
순회가 끝났다
k = 5 !
항상 기억할건, 리스트를 완벽하게 정리하지 않아도 된다는거. 뒤에 찌끄레기(?) 4, 5, 남아도 우리에게 필요한건 k이기 때문에 ㄱㅊ
* range(6) : 0,1,2,3,4,5 (0부터 시작해서 6개의 숫자 생성)
* range(1,6): 1,2,3,4,5 (1부터 시작해서 6-1까지의 숫자 생성)
그만 좀 헷갈립시다 -_- 어쨌든 무조건 뒤숫자는 포함 안된다는 거!!!
🥳 배운점
뿌엥...
'LeetCode 코딩테스트' 카테고리의 다른 글
Python 파이썬 sort(), sorted() 차이점 (0) | 2024.07.08 |
---|---|
Python append(), extend() 차이점 (0) | 2024.07.04 |
BST: Kth Smallest Node (어려웠다ㅜ^ㅜ) (0) | 2024.07.04 |
BST: Validate BST (0) | 2024.07.04 |
27. Remove Element (1) | 2024.07.03 |