【Leetcode】Remove Duplicates from Sorted Array II

题目链接:https://leetcode.com/problems/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

思路 :

在http://blog.csdn.net/yeqiuzs/article/details/50165201 的基础上加个计数器表示元素重复次数,当它大于2的时候考虑删除。

算法:.

	public int removeDuplicates(int[] nums) {
		int count = 0;//需要删除元素的个数
		int dups = 1; //每个重复元素的次数
		for (int i = 1; i < nums.length; i++) {
			if (nums[i] == nums[i - 1]) {
				dups++;
				if (dups > 2)//当重复元素大于2的时候才需要考虑删除
					count++;
			}else{
				dups = 1;//重置
			}
			nums[i - count] = nums[i];
		}
		return nums.length - count;
	}


你可能感兴趣的:(【Leetcode】Remove Duplicates from Sorted Array II)