一、题目叙述:
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 1
, 1
, 2
, 2
and 3
. It doesn't matter what you leave beyond the new length.
Subscribe to see which companies asked this question.
二、解题思路:
Medium题。
思路:
(1)倒着遍历数组,若当前元素与其前前一个元素的值不同,计数加1;否则,将后续元素前移。
(2)注意当数组元素小于等于2的情况。
三、源码:
import java.util.Arrays;
public class Solution
{
public int removeDuplicates(int[] nums)
{
if (nums.length <= 2) return nums.length;
int count = 2;
for (int i = nums.length - 1; i >= 2; i--)
{
if (nums[i] != nums[i - 2])
count ++;
else
for (int j = i; j < nums.length - 1; j ++)
nums[j] = nums[j + 1];
}
System.out.println(Arrays.toString(nums));
return count;
}
public static void main(String args[])
{
Solution solution = new Solution();
int[] nums = {1, 1, 1, 2, 2, 3};
System.out.println(solution.removeDuplicates(nums));
}
}