LeetCode: Remove Duplicates from Sorted Array II

題目

https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/


分析

和Remove Duplicates from Sorted Array類似, 

從前向後遍歷該序列, 如果該元素和前一元素相同則重複數加1。

只不過只有重複數小於等於2時才把該元素排到數組前面。



代碼

class Solution
{
public:
	int removeDuplicates(int A[], int n)
	{
		if (n < 1)
			return n;
		int count = 1;
		int dup_times = 1;
		for (int i = 1; i < n; i++)
		{
			if (A[i] == A[i-1])
				dup_times++;
			else
				dup_times = 1;

			if (dup_times <= 2)
				A[count++] = A[i];
		}
		return count;
	}
};



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