-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveDuplicatesFromSortedArrayII.java
More file actions
53 lines (46 loc) · 1.49 KB
/
RemoveDuplicatesFromSortedArrayII.java
File metadata and controls
53 lines (46 loc) · 1.49 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package leetcode;
/**
* RemoveDuplicatesFromSortedArrayII
* https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii/
* 80. 删除有序数组中的重复项 II
* https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii/solution/yuan-di-fu-gai-by-oshdyr-i7o1/
*
* @since 2021-04-06
*/
public class RemoveDuplicatesFromSortedArrayII {
public static void main(String[] args) {
RemoveDuplicatesFromSortedArrayII sol = new RemoveDuplicatesFromSortedArrayII();
int[] arr = {0, 0, 1, 1, 1, 1, 2, 3, 3};
int res = sol.removeDuplicates(arr);
for (int i = 0; i < res; i++) {
System.out.println(arr[i] + ", ");
}
System.out.println();
int[] arr2 = {1, 1, 1, 2, 2, 3};
int res2 = sol.removeDuplicates(arr2);
for (int i = 0; i < res2; i++) {
System.out.println(arr2[i] + ", ");
}
System.out.println();
}
public int removeDuplicates(int[] nums) {
int gap = 0;
int last = nums[0] - 1;
int lastTimes = 0;
for (int next = 0; next < nums.length; next++) {
if (nums[next] == last) {
lastTimes++;
if (lastTimes > 2) {
gap++;
}
} else {
last = nums[next];
lastTimes = 1;
}
if (gap > 0) {
nums[next - gap] = nums[next];
}
}
return nums.length - gap;
}
}