码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 【 Remove Duplicates from Sorted Array 】python 实现

时间:2015-01-16 22:14:33      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:

题目

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

 1 class Solution:
 2     # @param a list of integers
 3     # @return an integer
 4     def removeDuplicates(self, A):
 5         if len(A) == 0:
 6             return 0
 7         
 8         curr = 0
 9         for i in range(0, len(A)):
10             if A[curr] != A[i] :
11                 A[curr+1],A[i] = A[i],A[curr+1]
12                 curr += 1
13         return curr+1

 

思路

首先排除长度为0的special case

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

Tips: 注意curr是数组元素的下标从0开始,所以再最后返回时要返回curr+1

leetcode 【 Remove Duplicates from Sorted Array 】python 实现

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4229813.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!