Created
July 9, 2016 14:13
-
-
Save tiagopereira17/91b83a293a5441e06bafb07c1272794c to your computer and use it in GitHub Desktop.
Find an index of an array such that its value occurs at more than half of indices in the array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package leader; | |
import java.util.Stack; | |
public class Dominator { | |
public int solution(int[] A) { | |
if(A == null || A.length == 0) { | |
return -1; | |
} | |
Stack<Integer> stack = new Stack<>(); | |
for(int i = 0; i < A.length; i++) { | |
if(stack.isEmpty()) { | |
stack.push(A[i]); | |
continue; | |
} | |
if(stack.peek() != A[i]) { | |
stack.pop(); | |
} else { | |
stack.push(A[i]); | |
} | |
} | |
if(stack.isEmpty()) { | |
return -1; | |
} | |
int candidate = stack.pop(); | |
int counter = 0; | |
int candidateIndex = -1; | |
for(int i = 0; i < A.length; i++) { | |
if(A[i] == candidate) { | |
if(candidateIndex == -1) { | |
candidateIndex = i; | |
} | |
counter++; | |
} | |
} | |
if(counter <= (A.length / 2.0)) { | |
return -1; | |
} | |
return candidateIndex; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment