보석 쇼핑 문제를 풀고 나서, two pointers에 익숙해지면 좋겠다는 생각이 들었다. (특히, 시간초과 처리할 때)
leet code에 two pointers라는 tag가 따로 있길래 two pointers easy만 다 뿌시기를 하려고 한다.
문제
Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
제출 코드
class Solution: def removeDuplicates(self, nums: List[int]) -> int: if len(nums) == 0: return ele = nums[0] start = 1 while start < len(nums): if ele == nums[start]: del nums[start] else: ele = nums[start] start += 1
문제
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
제출 코드
class Solution: def removeElement(self, nums: List[int], val: int) -> int: if len(nums) == 0: return start = 0 while start < len(nums): if nums[start] == val: del nums[start] else: start += 1 print(nums)