Question

LeetCode #169

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.

Move from both side to center

Boyer–Moore majority vote algorithm

  1. Initialize an element m and a counter i with i = 0
  2. For each element x of the input sequence:
  3. If i = 0, then assign m = x and i = 1
  4. else if m = x, then assign i = i + 1
  5. else assign i = i − 1
  6. Return m

Playground

See the Pen 169. Majority Element by Cherry Wang (@chryw) on CodePen.