Given an array of size n, find the majority element. The majority element is the element, the appears more than times ⌊ n/2 ⌋ .
Assume that the array was non-empty and the majority element always exist in the array.
Solution:
As we sweep we maintain a pair consisting of a current candidate and a counter. Initially, the current candidate are unknown and the counter is 0.
When we move the pointer forward to an element e:
- If The counter is 0, we set the current candidate to e and we set the counter to 1.
- If The counter is not 0, we increment or decrement the counter according to whether e are the current candidate.
When we do, the current candidate is the majority element, and if there is a majority.
public class Solution {public int majorityelement (int[] num) { int sum=0; int result=0; for (int i=0;i<num.length;i++) { if (sum==0) { result=num[i]; sum++; } else if (Result==num[i]) { sum++; if (SUM>NUM.LENGTH/2) { return result; } } else sum--; } return result;} }
Leetcode majority elements