LeetCode 80 Remove Duplicates from Sorted Array II (Python详解及实现)
来源:互联网 发布:ftp文件服务器软件 编辑:程序博客网 时间:2024/06/02 04:13
【题目】
Follow up for "RemoveDuplicates":
What if duplicates are allowed at mosttwice?
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 matterwhat you leave beyond the new length.
给定一个数组,数组中的数字最多允许出现两次,若大于两次则保留两个该数字,最后返回数组长度
【思路】
定义一个标志位exist,为True则表明该数字已经出现两次,定义一个指针pstart,指示当前数组有效位置。
【Python实现】
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 8 15:32:54 2017
@author: Administrator
"""
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
size = len(nums)
if size == 0 or size == 1:
return size
pstart = 1
i = 1
tmp = nums[0]4
exist = False
while i < size:
if nums[i] == tmp:
if not exist:#未检测到两个相同数字
nums[pstart] = tmp
pstart += 1
exist =True
else:#不相同的情况
tmp = nums[i] #更新tmp
exist = False
nums[pstart] = tmp#用当前数字替换pstart所在位置的数
pstart += 1
i += 1
print(nums[:pstart])
return pstart
if __name__ == '__main__':
nums = [1,1,1,2,2,3,4,4,4,5]
S = Solution()
S.removeDuplicates(nums)
- LeetCode 80 Remove Duplicates from Sorted Array II (Python详解及实现)
- 【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
- LogisticRegression Digital
- Git版本控制系统之基本使用
- Android onTouchEvent 随手指移动时的抖动
- php 关键字static
- Hdu3473 Minimum Sum(划分树)
- LeetCode 80 Remove Duplicates from Sorted Array II (Python详解及实现)
- W7下QT5.8+opencv2.4.9+ffmpeg
- 洛谷P3374 [模板]树状数组1
- SVM理解
- ks文件示例
- java构造方法练习
- 【NYOJ-844】 A+B Problem(V)
- Camera.WorldToScreenPoint
- Cocos2d-JS极速调试技巧