【LEETCODE】80-Remove Duplicates from Sorted Array II [Python]
2016-01-21 20:00
615 查看
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 of
nums being 1, 1,
2, 2 and
3. 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:
错误分析:
第二个图,如果遇到多余3个相等的数字的时候,就会给出错误答案
第一个图,用一个 while 把第二个图的错误改过来了,但是结果数组的顺序又被搞乱了,虽然要求是返回 length,但是内部会检测是否保证原有大小顺序
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 of
nums being 1, 1,
2, 2 and
3. 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,但是内部会检测是否保证原有大小顺序
相关文章推荐
- Python学习练习:批量移动文件
- 我收藏的有关Python的电子书和资料
- Python Class 的实例方法/类方法/静态方法
- Using Eclipse with PyDev to build a Python development environment on Windows platform
- python 学习笔记1——数据类型、字符串、运算符
- python 文件中的__name__是什么?
- Python Class的实例属性/类属性
- python实战系列之通过libvirt操作KVM(六)
- Python中用timeit计时及注意事项
- Python中零碎知识点记录
- selendroid自动化环境安装和官方demo测试(python版本)
- python学习------------异常以及反射
- 用python实现的抓取腾讯视频所有电影的爬虫
- Python登录大连交通大学教务在线实现成绩查询
- 用python编写的抓京东商品价格的爬虫
- 用python编写的抓京东商品价格的爬虫
- python[二]:Eclipse安装下载python插件
- 深刻理解Python中的元类(metaclass)
- Python数据
- Python 多线程学习05 条件变量 Condition