Remove Duplicates from Sorted Array python 题解

来源:互联网 发布:android程序员校招 编辑:程序博客网 时间:2024/06/04 22:48

Remove Duplicates from Sorted Array python 题解

题意描述

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].

给定一个排好序的数组,去掉重复的元素,只让相同的元素只出现一次,返回新数组的长度
题目有个要求就是不允许开辟新的数组空间

分析思路
这道题类似实现C++ 中的去重操作,大致思路是遍历一遍数组将所有重复元素取第一个依次放到数组的最前面,然后截取数组的前半段即可
具体实现:遍历数组,用start记录遇到的每次遇到第一个重复元素要调整到的位置:这里start初值为1而不是0,因为新数组的第一个元素和旧数组是一样的,用keyValue记录遇到的重复元素,遍历数组,每次遇到新的重复元素,则更新keyValue,然后将该元素放到start指示的位置上,然后start向后挪一位,最后把原数组前半段没有重复元素的部分作为新数组(题目要求必须进行截取,否则WA),此时start的值就是新数组长度。

Python代码实现如下:

class Solution:    # @param a list of integers    # @return an integer    def removeDuplicates(self, A):        if A==[]: return 0        start=1;keyValue=A[0];length=len(A)        for i in range(length):            if A[i]!=keyValue:                keyValue=A[i]                A[start]=A[i]                start+=1        A=A[:start]        return start
0 0
原创粉丝点击