赞
踩
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 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 。
你不需要考虑数组中超出新长度后面的元素。
优点是很容易理解, 缺点是扩展性差, 只能解决最多保留两个元素的问题。
具体解法:
class Solution { public int removeDuplicates(int[] nums) { int index = 1; for(int i = 1; i < nums.length; i ++) { if(nums[i] == nums[i - 1]) { if(i == nums.length - 1 || nums[i] != nums[i + 1]) { nums[index ++] = nums[i]; } } else { nums[index ++] = nums[i]; } } return index; } }

很简洁的思路,利用了游标 index 自身的特点。
扩展性强,可以解决保留1, 2, 3 … N 个数的问题。将下面的 2 换成对应数量的数字即可。
具体看注释。
class Solution { public int removeDuplicates(int[] nums) { if(nums.length <= 2) return nums.length; // index 值代表有效长度 // 时刻记住 index 指向当前有效放置位置索引值 +1 的位置 // 前两个必定符合要求,直接跳过,从 2 开始 int index = 2; for(int i = 2; i < nums.length; i ++) { // 判断是否已经有了两个重复的 if(nums[i] != nums[index - 2]) nums[index ++] = nums[i]; } return index; } }

双指针的扩展性也比较强,可以解决保留 1,2, 3 … N 个数的问题。只需要将下述代码的 step 换成对应数字。
具体解法:
class Solution { public int removeDuplicates(int[] nums) { final int step = 2; if(nums.length <= step) return nums.length; int i = 0; int j = 0; int oldJ = -1; while(j < nums.length) { if(j == nums.length - 1 || nums[j] != nums[j + 1]) { int k = step; while(k -- > 0 && j >= ++ oldJ) { nums[i ++] = nums[j]; } oldJ = j; } j ++; } return i; } }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。