-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathCountDistinctSlices_SimpleLowPerformance.java
More file actions
40 lines (30 loc) · 1.14 KB
/
CountDistinctSlices_SimpleLowPerformance.java
File metadata and controls
40 lines (30 loc) · 1.14 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
// This solution is simple and correct, but with low performance (100% correct, 40% performance)
package CountDistinctSlices;
import java.util.*;
class Solution {
public int solution(int M, int[] A) {
// key point: using "set" for "each leftEnd"
Set<Integer> set = new HashSet<>();
int leftEnd =0;
int rightEnd =0;
int numDistinct =0;
while(leftEnd < A.length){
rightEnd = leftEnd; // for each time, rightEnd bigins at leftEnd
while(rightEnd < A.length){
if( set.contains( A[rightEnd] ) == false){ // distinct cases
numDistinct++;
if(numDistinct == 1_000_000_000)
return 1_000_000_000;
set.add(A[rightEnd]);
}
else{ // not distinct cases (then, break~!!)
break;
}
rightEnd++;
}
set.clear(); // for next leftEnd
leftEnd++;
}
return numDistinct;
}
}