Majority Element
Introduction
Given an array of size n, find the majority element. The majority element is the element that appears more than n/2 times.
You may assume that the array is non-empty and the majority element always exist in the array.
Solution
A simple naive method is to sort array first and return the middle item, but the time complexity is O(N*log(N)). A better O(N) solution uses Moore Voting algorithm that keeps a temporary major element and update it while traversing the whole array. Use count to count the occurrence of same element by incrementing it and decrement it when encounter a different number, replace major element with current number when count = 0. As the number of majority element is larger than the rest of numbers, it won’t be cancelled out and stay at the end.
1 | public class MajorityElement { |