easy/array 26번 성공

This commit is contained in:
2026-07-08 17:13:07 +09:00
parent 97646fa87c
commit a6eb2d156d

30
easy/array/26.py Normal file
View File

@@ -0,0 +1,30 @@
# Remove_Duplicates_from_Sorted_Array
class Solution:
def removeDuplicates(self, nums: list[int]) -> int:
nums[:] = list(dict.fromkeys(nums))
return len(nums)
## 투포인터를 쓴 공간복잡도 O(1) 풀이법
class Solution:
def removeDuplicates(self, nums: list[int]) -> int:
unique_pointer = 1
for i in range(1, len(nums)):
if nums[i] != nums[i-1]:
nums[unique_pointer] = nums[i]
unique_pointer += 1
return unique_pointer
"""
걸린 시간: 10분
시간 복잡도: nums를 dict로 변환하고(key는 요소, value는 none) 다시 리스트로 바꾸기 때문에 O(n)이다.
해설: 중복을 없애기 위해 dict와 set을 생각했지만, set은 순서 보장이 되지 않기 때문에 dict으로 변환한 뒤, 다시 리스트로 바꾸는 과정을 생각했다.
이렇게 하면 따로 메모리를 만들어서 공간복잡도가 O(n)이 되는데, 투 포인터를 활용하면 공간복잡도를 O(1)로 할 수 있다.
첫 번째 포인터는 중복이 아닌 것들이 나올때 초기화할 위치이고, 두 번째 포인터는 요소 전체를 순회하는 포인터이다.
시간복잡도는 전체 요소를 보기 때문에 마찬가지로 O(n)이다.
이 방식은 오름차순이라고 문제에서 제시했기 때문에 중복된 것들을 기억할 필요 없어져서 가능한 풀이이다.
"""