码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Remove Duplicates from Sorted Array

时间:2017-07-03 16:30:23      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:leetcode   sort   长度   his   重复   常见   代码   ted   appear   

 题目内容

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.

题目思路

本题难度等级: easy

本题要求的是原地进行处理,而且不能够申请新的空间。本题采用的方法是数组当中非常常见的处理方法:快慢指针

方法是:分别设立两个指针index,i。初始情况下,index和i都指向数组的第一个元素。i为快指针,index为慢指针。 i从第一个元素一直扫描到最后一个元素。index是慢指针,仅当nums[i]!=nums[index]的时候,index才会自增1。当扫描结束的时候,index指向的是不重复数组的最后一个元素,其长度为index+1

Python代码

class Solution:
    # @param a list of integers
    # @return an integer
    def removeDuplicates(self, A):
        if not A:
            return 0
        index= 0
        for i in range( len(A)):
            if A[i] != A[index]:
                index+= 1
                A[index] = A[i]
        return index+ 1

 

[LeetCode] Remove Duplicates from Sorted Array

标签:leetcode   sort   长度   his   重复   常见   代码   ted   appear   

原文地址:http://www.cnblogs.com/chengyuanqi/p/7111103.html

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