반응형
https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
Remove Duplicates from Sorted Array - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
오름차순으로 정렬된 중복되는 숫자가 존재하는 array에서 중복 숫자를 제거하는 문제
제거 하는 문제는 일반적으로 뒤에서부터 루프를 돌아야 index 관리가 편하다.
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
for i in range(len(nums)-1, 0 , -1):
if nums[i] == nums[i-1]:
nums.pop(i)
return len(nums)
time complexity: O(n) 알고리즘 완성
이게 아마 코딩 테스트에서 원하는 답이었을듯?
굳이 더 있어보이게 짠다면 if문을 한줄로 줄이거나 SCE(Short-circuite evaluation) 사용
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
for i in range(len(nums)-1, 0 , -1):
nums[i] == nums[i-1] and nums.pop(i)
return len(nums)
반응형
'Computer Science > CODINGTEST_PRACTICE' 카테고리의 다른 글
[LeeCode] 53. Maximum Subarray (0) | 2022.12.18 |
---|---|
[LeetCode] 217. Contains Duplicate (0) | 2022.12.18 |
[LeetCode] 21. Merge Two Sorted Lists 기록 (0) | 2022.11.16 |
[LeetCode] 151. Reverse Words in a String 기록 (0) | 2022.11.13 |
[LeetCode] 20. Valid Parentheses 기록 (2) | 2022.11.12 |