【LeetCode】2.Remove Duplicates from Sorted Array II

题目描述(Medium)

Given a sorted array nums, remove the duplicates in - place such that duplicates appeared at most twice and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in - place with O(1) extra memory.

题目链接

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

Example 1:

Given nums = [1, 1, 1, 2, 2, 3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It doesn't matter what you leave beyond the returned length.

Example 2:

 Given nums = [0, 0, 1, 1, 1, 1, 2, 3, 3],
Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.
It doesn't matter what values are set beyond the returned length.

算法分析

方法一:加一个变量记录元素出现的次数即可;

方法二:和当前保存位置的左边第二个元素比较,决定是否符合条件;

提交代码(方法一):

class Solution {
public:
	int removeDuplicates(vector<int>& nums) {
		if (nums.empty()) return 0;

		int j = 0, times = 1;
		for (int i = 1; i < nums.size(); ++i)
		{
			if (nums[i] != nums[j])
			{
				nums[++j] = nums[i];
				times = 1;
			}
			else
				if (++times <= 2) nums[++j] = nums[i];
		}

		return j + 1;
	}
};

提交代码(方法二):

class Solution {
public:
	int removeDuplicates(vector<int>& nums) {
		if (nums.size() <= 2) return nums.size();

		int j = 2;
		for (int i = 2; i < nums.size(); ++i)
		{
			if (nums[i] != nums[j - 2])
				nums[j++] = nums[i];
		}

		return j;
	}
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, vector<int>& nums)
{
	if (testName != nullptr)
		printf("%s begins: \n", testName);

	Solution s;
	int len = s.removeDuplicates(nums);

	for (int i = 0; i < len; i++)
		cout << nums[i] << " ";
	cout << endl;
}

int main(int argc, char* argv[])
{
	Test("Test1", vector<int>());

	Test("Test2", vector<int>(10, 1));

	vector<int> test = { 1, 1, 1, 2, 2, 3 };
	Test("Test3", test);

	test = { 0, 0, 1, 1, 1, 1, 2, 3, 3 };
	Test("Test4", test);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/81559250