0%

LeetCode-80

题目

结果

代码

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
class Solution {
public int removeDuplicates(int[] nums) {
int length = nums.length;
// false表示出现过一次,true表示出现过两次
Map<Integer, Boolean> map = new HashMap<>();
for (int i = 0; i < length; i++) {
if (!map.containsKey(nums[i])) { // 没出现过
map.put(nums[i], false);
} else if (!map.get(nums[i])) { //出现过一次
map.put(nums[i], true);
} else if (map.get(nums[i])) { // 出现过两次
removeNum(nums, i);
length--;
i--; // 点睛之笔
}
}
return length;
}

private void removeNum(int[] nums, int index) {
if (nums.length >= index + 1) {
System.arraycopy(nums, index + 1, nums, index, nums.length - 1 - index);
}
}
}

一边遍历数组一边修改,可能会产生意想不到的问题,尽量还是别这样做的好。