创建于 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即可。
网友评论