标签:blog os io for ar art cti div
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]
.
双指针的思路,但是这里容许两个重复,所以判断条件修改一下。
1st (5 tries)
class Solution { public: int removeDuplicates(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int i,j,k,count; for(i = 0;i < n;++i) { count = 0; int tmp = A[i]; j = i+2; while(j < n&&A[j] == tmp) { j++; count++; } if(count == 0) ; else { for( k = j; k < n;++k) { A[k-count] = A[k]; } } n -= count; } return n; } };
2nd(3 tries)
class Solution { public: int removeDuplicates(int A[], int n) { int start = 0; for(int i = 0;i < n;i++) { if(i == 0 || i == 1) { A[start++] = A[i]; } else { //using start if(A[i] == A[start-2]) { } else { A[start++] = A[i]; } } } return start; } };
【Leetcode】Remove Duplicates from Sorted Array II,布布扣,bubuko.com
【Leetcode】Remove Duplicates from Sorted Array II
标签:blog os io for ar art cti div
原文地址:http://www.cnblogs.com/weixliu/p/3924315.html