题目
删除排序数组中的重复项 II
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
来源:力扣(LeetCode)
题目链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii
解答
我想到了两种解法,一种比较好想,但耗时长一些,另一种耗时短一些但不容易想到。
第一种:
public int removeDuplicates(int[] nums) {
int count = 0;
int f = nums.length;
// count用来记录字符出现次数
// f用来记录有效字符长度
//i用来遍历数组中的元素
//j用来匹配元素
for (int i = 0; i < nums.length; i++) {
count = 0;
for (int j = i; j < f; j++) {
if (nums[j] > nums[i]) { //j对应的数字大于i对应的
// 数组中的数字出现超过两次,i需要后移一位(+1)再执行i++,如果小于2次,直接去执行i++即可
if (count >= 2)
i = i + 1;
break;
} else {
if (nums[j] == nums[i]) { // 出现重复数字,次数count+1
count++;
}
if (count > 2) { // 次数超出两次,后面的字符串前移
f = f - 1;// 数组有效长度减一
for (int k = j; k < f; k++) {// 前移
if (k == f) { //到达有效长度结束
break;
} else {
nums[k] = nums[k + 1];
}
}
j = j - 1;//j后面的数组(包括j)前移一位,j的位置要向前移一位
}
}
}
}
return f;
}
第二种:
/*过程
* 0 0 1 1 1 1 2 2 2 4
* index-2 i(index)
*
* 0 0 1 1 1 1 2 2 2 4
* index-2 i(index)
*
* 0 0 1 1 1 1 2 2 2 4
* index-2 (index) i
*
* 0 0 1 1 1 1 2 2 2 4
* index-2 (index) i
*
* 0 0 1 1 2 1 2 2 2 4
* index-2 (index) i
* 0 0 1 1 2 2 2 2 2 4
* index-2 (index) i
* 0 0 1 1 2 2 2 2 2 4
* index-2 (index) i
* 0 0 1 1 2 2 4 2 2 4
* index-2 (index) i
*/
public static int removeDuplicates(int[] nums) {
if (nums.length <= 2)//如果数组长度小于等于2,之间返回数组的长度
return nums.length;
int index = 2;
for (int i = 2; i < nums.length; i++) {
if (nums[i] != nums[index - 2])
//如果i位置对应的元素与index-2位置所对应的元素不等,把nums[i]对应的值赋给nums[index++]
nums[index++] = nums[i];
}
return index;//返回index的值
}
}