forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 8
/
_80.java
49 lines (40 loc) · 1.1 KB
/
_80.java
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
package com.fishercoder.solutions;
import java.util.ArrayList;
/**
* Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5,
with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
*/
public class _80 {
public int removeDuplicates(int[] nums) {
int counter = 0;
int len = nums.length;
if (len == 0) {
return 0;
}
if (len == 1) {
return 1;
}
if (len == 2) {
return 2;
}
ArrayList<Integer> a = new ArrayList();
a.add(nums[0]);
a.add(nums[1]);
for (int i = 2; i < len; i++) {
if (nums[i] != nums[i - 1]) {
a.add(nums[i]);
} else if (nums[i] != nums[i - 2]) {
a.add(nums[i]);
}
}
counter = a.size();
for (int i = 0; i < counter; i++) {
nums[i] = a.get(i);
}
return counter;
}
}