leecode -- 80. 删除排序数组中的重复项 II

题目要求原地修改,返回数组长度。

用两个指针标记数组的位置,一个是遍历数组,一个是记录“新数组”的 tail

 1     public static int removeDuplicates(int[] nums) {
 2             if (nums.length == 0) {
 3             return 0;
 4         }
 5         int j = 0;
 6         int k = nums[0] - 1;//初始化一个最小元素
 7         int times = 0;
 8         for (int i = 0; i < nums.length; i++) {
 9             if (nums[i] > k) { // 遍历过程中值发生变化
10                 nums[j++] = nums[i];
11                 k = nums[i];
12                 times = 0;
13             } else if (times < 1) { // 相等元素第二次遍历到时
14                 nums[j++] = nums[i];
15                 k = nums[i];
16                 times++;
17             }
18         }
19         return j;
20     }

猜你喜欢

转载自www.cnblogs.com/hansc-blog/p/9283877.html