26. Remove Duplicates from Sorted Array [easy] (Python)

题目链接

https://leetcode.com/problems/remove-duplicates-from-sorted-array/

题目原文

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.

题目翻译

给定一个有序数组,直接在数组中删除重复元素,使每个元素只出现一次,并返回长度。不允许申请额外空间存放另一个数组,你只能使用O(1)空间复杂度在原数组操作。
比如,给定数组nums = [1,1,2],你的函数应该返回2,同时数组nums的前两个元素是1和2。在数组长度之外的值是多少无所谓。

思路方法

思路一

用两个指针,一个指针用于扫描遍历整个列表,另一个指针始终指向下一个数字要写入列表的位置。效果相当于在遍历列表的时候,将不同的数字重新写入到原数组。

代码

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums)==0:
            return 0
        cur = 0
        for i in range(1, len(nums)):
            if nums[i] != nums[cur]:
                cur += 1
                nums[cur] = nums[i]
        return cur+1

思路二

用一个计数器记录当前有多少个重复数字,以此来决定下一个要写入数组的数字的位置,以及当遍历完数组时得到新数组的长度。

代码

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = 0
        for i in range(1, len(nums)):
            if nums[i] == nums[i-1]:
                count += 1
            else:
                nums[i-count] = nums[i]
        return len(nums) - count

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51589013

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值