Remove Duplicates from Sorted Array python 题解

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值