Find majority element (Boyer-Moore)
Java
Medium
4 views
Problem Description
Task: assume there is a majority element (> n/2). Return it using O(1) space.
Output Format
Return value
Constraints
Assume majority always exists.
Official Solution
static int majority(int[] a){int cand=0,c=0;for(int x:a){if(c==0){cand=x;c=1;}else if(x==cand) c++; else c--; }return cand;}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!