题目链接
https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
题目原文
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.
题目大意
给定一个排好序的数组。修改这个数组使得每个数最多可以出现两次。返回去掉多余重复数组后的长度length
后面一直出错,研究了下别人的答案才意识到题目还有一个要求,就是要把排序后的数组依旧保存到原nums[]数组中,要保证前length位的nums里面存的数就是已经排序后的数据。
比如【1,1,1,2,2,3,4】返回去重后数组个数6,去重后的nums的前6位应该是【1,1,2,2,3,4】,另外保存到一个数组中会报错
英语不好的伤痛!
1 #encoding=utf-8 2 class Solution(object): 3 def removeDuplicates(self, nums): 4 """ 5 :type nums: List[int] 6 :rtype: int 7 """ 8 9 count = 1 10 j = 0 #j是重复数字的个数 11 if not nums: 12 return 0 13 if len(nums) == 1: 14 return 1 15 if len(nums) == 2: 16 return 2 17 for i in range(1,len(nums)): 18 if nums[i-1] != nums[i]: 19 j = 0 20 count += 1 21 nums[count-1] = nums[i] #更替nums 22 else: 23 j += 1 24 if j == 1: 25 count += 1 26 nums[count-1] = nums[i] 27 return count,nums 28 29 30 31 nums = [1,1,1,2,3,3,3,4,4,4] 32 s = Solution() 33 print s.removeDuplicates(nums)
效果出乎意料的好,超越了100%的人,开心,遇到问题没法解决的时候一定要多借鉴别人的想法,反思自己的不足,找到自己的错误
借鉴的解法:http://www.cnblogs.com/loadofleaf/p/5366950.html,性能不是很好