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 =
Your function should return length =
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 ;
}
};
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,
2and
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 ;
}
};
相关文章推荐
- Leetcode NO.80 Remove Duplicates from Sorted Array II
- LeetCode--No.80--Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II [27]
- LeetCode Remove Duplicates from Sorted Array II
- 【LeetCode】Remove Duplicates from Sorted Array II
- LeetCode:Remove Duplicates from Sorted Array II
- LeetCode 080 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 (Java)
- leetcode_Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- 【leetcode c++】80 Remove Duplicates from Sorted Array II
- [LeetCode][Java] 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-80-Remove Duplicates from Sorted Array II(递归)-Medium