[LeetCode]Remove Duplicates from Sorted Array II

題目:

Remove Duplicates from Sorted Array II

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].


思路:

前面是刪除重複所有的,這題是保留兩個,想當然的做了,結果沒考慮清楚,耗時不少。

C++ AC代碼:

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if( n < 3)
		    return n;
		int i=0, j=1,cnt = 1;
		for ( ; j<n; j++){
		    if( A[i] == A[j] ){
			    if ( cnt == 1 ){
				    A[++i]=A[j];					
				}
				cnt++;
			}
			else{
			    A[++i] = A[j];
				cnt = 1;
			}
		}
		return i+1;
    }
};

運行時間 88ms

發佈了55 篇原創文章 · 獲贊 9 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章