-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
Copy path26.java
88 lines (85 loc) · 2.56 KB
/
26.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
__________________________________________________________________________________________________
1msclass Solution {
public int removeDuplicates(int[] nums) {
if(nums.length < 2) return nums.length;
int currentIdx = 0;
int nextIdx = 1;
while(nextIdx < nums.length ) {
while(nextIdx < nums.length && nums[currentIdx] == nums[nextIdx]) {
nextIdx++;
}
if(nextIdx < nums.length)
nums[++currentIdx] = nums[nextIdx];
nextIdx++;
}
return currentIdx+1;
}
}
__________________________________________________________________________________________________
3ms
class Solution {
public int removeDuplicates(int[] nums) {
int slow = 0, fast = 0;
Set<Integer> set = new HashSet<>();
int res = 0;
while(fast < nums.length) {
if(set.add(nums[fast])) {
nums[slow] = nums[fast];
res++;
slow++;
}
fast ++;
}
return res;
}
}
__________________________________________________________________________________________________
5ms
class Solution {
public int removeDuplicates(int[] nums) {
Set<Integer> set = new TreeSet<>();
for(int i = 0; i<nums.length; i++){
set.add(nums[i]);
}
Iterator<Integer> iterator = set.iterator();
int i = 0;
while (iterator.hasNext()){
nums[i++] = iterator.next();
}
return set.size();
}
}
__________________________________________________________________________________________________
36584 kb
class Solution {
public int removeDuplicates(int[] nums) {
int count = 0;
int j = 0;
for(int i = 1 ; i < nums.length ; i++){
if(nums[j]==nums[i]){
continue;
}
else{
nums[++j] = nums[i];
//nums[i] = 0;
count++;
}
}
return count+1;
}
}
__________________________________________________________________________________________________
36720 kb
public class Solution {
public int removeDuplicates(int[] A) {
if (A == null || A.length == 0) return 0; //can do "if len < 2 return A.len"
int pre = 0;
for (int i = 1; i < A.length; i++) {
if (A[i] != A[pre]) {
A[++pre] = A[i];
}
}
return pre + 1;
}
}
__________________________________________________________________________________________________