Nameless Site

But one day, you will stand before its decrepit gate,without really knowing why.

0%

删除排序数组中的重复项

来源Leetcode第26题删除排序数组中的重复项

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

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

示例 1:

给定数组 nums = [1,1,2],

函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。

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

这题和之前的随机的第80题是一样的2333,代码就在之前的改改就好了

2种代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
*First solution
*/
public int removeDuplicates(int[] nums) {
int i = 0;
for (int n : nums)
if (i < 1 || n > nums[i-1])
nums[i++] = n;
return i;
}

/*
*Second solution
*/
public int removeDuplicates(int[] nums) {
int m = 0;
for (int i = 0; i < nums.length;) {
if (i < nums.length - 1 && nums[i] == nums[i + 1]) {
int val = nums[i]; //记录当前值
nums[m++] = nums[i++]; //对数组进行1次操作
while (i < nums.length && nums[i] == val) //如果2个数之后的数据元素仍与之前相等就跳过
i++;
} else
nums[m++] = nums[i++]; //最后两个元素无所谓从不重复,直接复制就完事了
}
return m;
}