Leetcode P26 Remove Duplicates from Sorted Array @python Lang (LL)

9 篇文章 0 订阅
9 篇文章 0 订阅

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

Content:
在这里插入图片描述
第一次分析题目的时候出现的错误
本题要求return 去掉重复key后的array长度
但是特别注意的是**** first length elements modified ! and doesn’t matter what values are set beyond the returned length.

Method 1: two pointers
Algorithm:

  1. set two pointers i, j
  2. i points to current position (removes the duplicate keys), j traverse the whole array
  3. 当J 碰到不重复的,i move to next position, 并且将j值赋给i。.
  4. return i + 1 (because i is index)

Code:

def removeDuplicates(nums):
    if len(nums) == 0:
        return 0
    i = 0
    for j in range(1,len(nums)):
        if nums[i] != nums[j]:
            i += 1
            nums[i] = nums[j]
    return i + 1

Method 2: counter (recode the number of duplicate keys)
Algorithm:

  1. set a counter c = 0 to record the number of duplicate keys
  2. traverse i, if nums[i]==nums[i-1], c+=1
  3. else: nums[i-c] = nums[i]
  4. return len(nums)-c

Time complexity: O(n)

Code:

def removeDuplicates(self,nums):
    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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值