-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathDominator.java
More file actions
51 lines (41 loc) · 1.45 KB
/
Copy pathDominator.java
File metadata and controls
51 lines (41 loc) · 1.45 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
// you can also use imports, for example:
// import java.util.*;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
import java.util.Stack;
class Solution {
public int solution(int[] A) {
// majority vote algorithm
int candidateIndex = -1;
int counter = 0;
for(int i=0; i<A.length; i++) {
// first element, init
if(candidateIndex < 0) {
candidateIndex = 0;
counter++;
continue;
}
// same element, increment counter
if(A[i] == A[candidateIndex]) { counter++; }
// different element
// .. decrement counter if possible
// .. otherwise set current index as candidate
else {
if( counter > 0) { counter--; }
else {
counter = 0;
candidateIndex = i;
}
}
}
return (isDominator(A, candidateIndex)) ? candidateIndex : -1;
}
private boolean isDominator(int[] A, int candidateIndex) {
if(candidateIndex < 0) return false;
int countOfCandidate = 0;
for(int element: A) {
if(element == A[candidateIndex]) { countOfCandidate++; }
}
return (countOfCandidate > A.length/2) ? true : false;
}
}