博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode80. Remove Duplicates from Sorted Array II(思路及python解法)
阅读量:2241 次
发布时间:2019-05-09

本文共 1001 字,大约阅读时间需要 3 分钟。

Given a sorted array nums, remove the duplicates  such that duplicates appeared at most twice and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array  with O(1) extra memory.

Example 1:

Given nums = [1,1,1,2,2,3], Your function should return length = 5, with the first five elements of numsbeing 1, 1, 2, 2

and 3 respectively.

Example 2:
Given nums = [0,0,1,1,1,1,2,3,3], Your function should return length = 7, with the first seven elements of numsbeing modified to 0, 0, 1, 1, 2, 3 and 3 respectively.


列表已经从小到大排序完了,删除数字重复出现次数大于2次的,需要原地操作。

所以只需要记录当前数字出现次数即可。dup表示当前数字出现的次数。

如果dup>2则删除当前数字,注意此时nums的长度,记录位置的n,重复次数dup都需要-1。

class Solution:    def removeDuplicates(self, nums: List[int]) -> int:        length=len(nums)        n=1        dup=1        while n
2: nums.remove(nums[n]) dup-=1 length-=1 n-=1 else: dup=1 n+=1

 

转载地址:http://ljrbb.baihongyu.com/

你可能感兴趣的文章
【LEETCODE】312-Burst Balloons
查看>>
【LEETCODE】232-Implement Queue using Stacks
查看>>
【LEETCODE】225-Implement Stack using Queues
查看>>
【LEETCODE】155-Min Stack
查看>>
【LEETCODE】20-Valid Parentheses
查看>>
【LEETCODE】290-Word Pattern
查看>>
【LEETCODE】36-Valid Sudoku
查看>>
【LEETCODE】205-Isomorphic Strings
查看>>
【LEETCODE】204-Count Primes
查看>>
【LEETCODE】228-Summary Ranges
查看>>
【LEETCODE】27-Remove Element
查看>>
【LEETCODE】66-Plus One
查看>>
【LEETCODE】26-Remove Duplicates from Sorted Array
查看>>
【LEETCODE】118-Pascal's Triangle
查看>>
【LEETCODE】119-Pascal's Triangle II
查看>>
word2vec 模型思想和代码实现
查看>>
怎样做情感分析
查看>>
用深度神经网络处理NER命名实体识别问题
查看>>
用 RNN 训练语言模型生成文本
查看>>
RNN与机器翻译
查看>>