leetcode 80:Remove Duplicates from Sorted Array II

题目:

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1122 and 3. It doesn't matter what you leave beyond the new length.

思路:

因为已经排好序了,我们只需看每个元素相同的个数,超过2个我们就删除多余的,然后将后面的元素往前移动,移动操作直接借用STL的move来完成。

但是从后面开始检测,更节省时间。

实现如下:

class Solution {
public:
	int removeDuplicates(vector<int>& nums) {
		int size = nums.size();
		if (size < 3) return size;
		int count = 1,flag=0;
		vector<int>::iterator last = nums.end();
		for (vector<int>::iterator i = nums.begin() + 1; i < last; ++i)
		{
			while (i != last && *i == *(i - 1))
			{
				++count;
				++i;
				flag = 1;
			}
			if (count >= 3)
			{
				last -= count - 2;
				move(i, nums.end(), i - count + 2);
				i -= (count - 2);
				count = 1;
			}
			else count = 1;
			if (flag == 1)
			{
				flag = 0;
				--i;
			}
		}
		return (last - nums.begin());
	}
};

下面提供更快、更简洁的方法,不需要移动数据。

记录元素个数,当第i个元素与前两个不相同时,就将该元素存到相应位置。

时间复杂度:O(n)

class Solution {
public:
	int removeDuplicates(vector<int>& nums) {
		int size = nums.size();
		if (size < 3) return size;
		int rear = 1;
		for (int i = 2; i < size; ++i)
			if (!(nums[i] == nums[rear] && nums[i] == nums[rear - 1])) nums[++rear] = nums[i];
		return rear + 1;
	}
};


你可能感兴趣的:(leetcode 80:Remove Duplicates from Sorted Array II)