Skip to content

Instantly share code, notes, and snippets.

@stephen-maina
Created May 1, 2015 15:02
Show Gist options
  • Save stephen-maina/70a81deb2a9d357e3862 to your computer and use it in GitHub Desktop.
Save stephen-maina/70a81deb2a9d357e3862 to your computer and use it in GitHub Desktop.
import java.util.Stack;
class Solution {
public int solution(int[] A) {
// write your code in Java SE 8
if(A.length==0){
return -1;
}
Stack<Integer> stack=new Stack<Integer>();
int size=0;
int dominatorIndex=0;
boolean wasEmpty=false;
for(int index=0;index<A.length;index++){
if(stack.empty()){
stack.push(A[index]);wasEmpty=true;
}
if(!stack.empty()&&stack.peek()!=A[index]){
stack.pop();
}else{
if(!stack.empty()&&wasEmpty==false){
stack.push(A[index]);
}
}
wasEmpty=false;
}
for(int index=0;index<A.length;index++){
if(!stack.empty()&&stack.peek()==A[index]){
size++;
dominatorIndex=index;
}
}
if(size<=A.length/2){
return -1;
}
return dominatorIndex;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment