标签:style blog class code c tar
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3]
,
Your function should return length = 5
,
and A is now [1,1,2,2,3]
.
题意:从一个已排序的数组中移除掉重复的元素,每个元素最多可重复两次
思路: 思路和Remove Duplicates from Sorted Array一样,不过要设置一个计数变量,表示当前值出现的次数
出现次数少于2可以加入到新数组,多于2则不可以。每次遇到一个新变量要把计数变量重新设置为1,加入新数组要加1
复杂度:时间O(n), 空间O(1)
相关题目:
class Solution { public: int removeDuplicates(int A[], int n){ if (n < 1) return 0; int c = 1; int j = 1; for(int i = 1; i < n; i++){ if (A[i] == A[i - 1]){ if(c < 2){ A[j++] = A[i]; c++; } }else{ A[j++] = A[i]; c = 1; } } return j; } };
Leetcode 线性表 Remove Duplicates from Sorted Array II,布布扣,bubuko.com
Leetcode 线性表 Remove Duplicates from Sorted Array II
标签:style blog class code c tar
原文地址:http://blog.csdn.net/zhengsenlie/article/details/25776973