創建于 20170308
原文鏈接:
https://leetcode.com/problems/remove-duplicates-from-sorted-array/?tab=Description
1 題目:
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 in place with constant memory.
For example,Given input array 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.
2 python 代碼:
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
i=0
for j in range(len(nums)):
if nums[i]!=nums[j]:
tmp=nums[j]
nums[j]=nums[i+1]
nums[i+1]=tmp
i+=1
j+=1
return i+1
3 算法解析
這是一個典型的雙指針問題。i是慢指針,j是快指針。
找到不重復的進行swap即可。