您的位置:首页 > 编程语言 > Python开发

leetcode 【 Remove Duplicates from Sorted Array 】python 实现

2015-01-16 21:31 141 查看
题目

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 A =
[1,1,2]
,

Your function should return length =
2
, and A is now
[1,2]
.

代码:oj测试通过 Runtime: 143 ms

class Solution:
# @param a list of integers
# @return an integer
def removeDuplicates(self, A):
if len(A) == 0:
return 0

curr = 0
for i in range(0, len(A)):
if A[curr] != A[i] :
A[curr+1],A[i] = A[i],A[curr+1]
curr += 1
return curr+1


思路

首先排除长度为0的special case

使用双指针技巧:用curr指针记录不含有重复元素的数据长度;另一个指针i从前往后走

Tips: 注意curr是数组元素的下标从0开始,所以再最后返回时要返回curr+1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: