Given a sorted array, 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.
Example:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.
Solution
思路:
a. 設(shè)定兩個(gè)哨兵,一個(gè)為遍歷(每次一定+1)的index,一個(gè)為去重后最尾元素的index
b. 遍歷的值如果遇到與去重后最尾值相等,遍歷index則持續(xù)+1
c. 最后返回去重結(jié)果最尾元素的index + 1
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
i, j = 0, 1
while j < len(nums):
while j < len(nums) and nums[j] == nums[i]:
j += 1
if j < len(nums):
nums[i + 1] = nums[j]
i += 1
j += 1
return i + 1