【LEETCODE】80-Remove Duplicates from Sorted Array II [Python]
来源:互联网 发布:c语言程序代码大全 编辑:程序博客网 时间:2024/06/06 15:34
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements ofnums being 1, 1,2, 2 and3. It doesn't matter what you leave beyond the new length.
题意:
接Remove Duplicates
如果允许重复的数字最多出现两次呢?
例:
给一个数组:nums = [1,1,1,2,2,3]
返回length = 5, 即 1, 1, 2, 2 and 3
思路:
两个指针 pre , cur
A[cur] 如果和 A[pre]及 A[pre-1]的值想等,则 cur进1,一直到 A[cur] 不再等于 A[pre]及 A[pre-1]
当不是上述情况时,pre进1, A[pre]换成 A[cur] ,cur进1,也就是把多余两个的数字,用后面的非重复数字替换掉
Python:
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ n=len(nums) if n<=2: return n pre=1 cur=2 while cur<n: if nums[cur]==nums[pre] and nums[cur]==nums[pre-1]: cur+=1 else: pre+=1 nums[pre]=nums[cur] cur+=1 return pre+1
错误分析:
第二个图,如果遇到多余3个相等的数字的时候,就会给出错误答案
第一个图,用一个 while 把第二个图的错误改过来了,但是结果数组的顺序又被搞乱了,虽然要求是返回 length,但是内部会检测是否保证原有大小顺序
0 0
- 【LEETCODE】80-Remove Duplicates from Sorted Array II [Python]
- 【Leetcode】【python】Remove Duplicates from Sorted Array/Remove Duplicates from Sorted Array II
- [leetcode] python Remove Duplicates from Sorted Array II
- 【LeetCode with Python】 Remove Duplicates from Sorted Array II
- LeetCode-Array-80 Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array II
- LeetCode-Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- LeetCode - Remove Duplicates from Sorted Array II
- LeetCode:Remove Duplicates from Sorted Array II
- LeetCode | Remove Duplicates from Sorted Array II
- iOS使用ionic实现混合式开发
- Return objects to enable chaining of functions
- 算法导论第三版习题5.1
- SimpleDateFormat线程安全的问题
- iOS文件管理,文件夹目录调取+缓存读取计算清除
- 【LEETCODE】80-Remove Duplicates from Sorted Array II [Python]
- 高质量JAVA代码编写规范
- hibernate3和hibernate4的区别
- Beaglebone Black更新系统的方法
- 当Java代码遇上抽象、重载加重写,一切都不美好了
- 64位Ubuntu12.04下安装arm-linux-gdb,以及解决no termcap library found的方法
- 关于assetbundle的详解等
- 链接
- 线索二叉树