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;
	}
};

本文章迁移自http://blog.csdn.net/timberwolf_2012/article/details/39546327

/** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/ /* var disqus_config = function () { this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; */ (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://chenzz.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })();