您的位置:首页 > 其它

LeetCode No.80 Remove Duplicates from Sorted Array II

2016-11-11 15:09 531 查看
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.

===================================================================

题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

题目大意:要求排序数组中每个数值最多出现两次,并返回新数组长度。

思路:记录每个数值个数,最多保留两个,边访问边记录。

参考代码:

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size() , ans = 0 ;
if ( n == 0 )
return 0 ;

for ( int i = 0 ; i < n ; i ++ )
{
int cur = nums[i] , sum = 1 ;
while ( i + 1 < n && nums[i+1] == cur )
{
i ++ ;
sum ++ ;
}
sum = sum > 2 ? 2 : sum ;
for ( int j = ans ; j < ans + sum ; j ++ )
nums[j] = cur ;
ans += sum ;
}
return ans ;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: