删除排序数组中的重复项II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39360985/article/details/84753374

给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。

不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。

示例 1:

给定 nums = [1,1,1,2,2,3],

函数应返回新长度 length = 5, 并且原数组的前五个元素被修改为 1, 1, 2, 2, 3 。

你不需要考虑数组中超出新长度后面的元素。

示例 2:

给定 nums = [0,0,1,1,1,1,2,3,3],

函数应返回新长度 length = 7, 并且原数组的前五个元素被修改为 0, 0, 1, 1, 2, 3, 3 。

你不需要考虑数组中超出新长度后面的元素。

说明:

为什么返回数值是整数,但输出的答案是数组呢?

请注意,输入数组是以**“引用”**方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。

你可以想象内部操作如下:

// nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝
int len = removeDuplicates(nums);

// 在函数里修改输入数组对于调用者是可见的。
// 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

题目分析:

删除排序数组中的重复项,使得每个元素最多出现两次,这跟此题删除排序数组中的重复项的区别就是可以使重复项出现两次。这就需要设置一个计数器计数。

代码实现:

public int removeDuplicates(int[] nums) {
   if (nums.length == 0)
       return 0;

   if (nums.length == 1)
       return 1;

   int i = 0;
   int j = i;
   int count = 0;
   int tempCount = 0;

   while (i < nums.length){
       if (j < nums.length && nums[j] == nums[i]){
           j++;
           tempCount++;
       }
       else {
           if (tempCount >= 2){
               count += 2;
               nums[i+1] = nums[i];
               i += 2;
           }
           else {
               count++;
               i++;
           }
           if (j >= nums.length)
               break;
           nums[i] = nums[j];
           tempCount = 0;
       }
   }

   return count;
}

主函数:

public static void main(String[] args) {
   A6 a = new A6();
   int[] nums = {1,1,1,2,2,3};
   int res = a.removeDuplicates(nums);
   System.out.println(res);

   for (int i = 0; i < res; i++) {
       System.out.print(nums[i] + " ");
   }
}

运行结果:

5
1 1 2 2 3

猜你喜欢

转载自blog.csdn.net/qq_39360985/article/details/84753374