leetcode練習 解題

Given a sorted array nums, remove the duplicates in-place such that each element appear only once 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.

解題

用兩個pointers,一快一慢。快的是用來loop那個list的,而慢的是用來寫入没有重複的數字。

代碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class (object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

slow = 0

for fast in range(len(nums)):
if fast == 0 or nums[fast-1]!=nums[fast]:
nums[slow]=nums[fast]
slow+=1

return slow