Note: https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm Good problem and intro to a new algorithm.
(nums []int)
| 3 | // Note: https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm |
| 4 | // Good problem and intro to a new algorithm. |
| 5 | func majorityElement(nums []int) int { |
| 6 | count := 0 |
| 7 | candidate := 0 |
| 8 | |
| 9 | for i := 0; i < len(nums); i++ { |
| 10 | // pick first candidate or last suffix brought count to 0 |
| 11 | if count == 0 { |
| 12 | candidate = nums[i] |
| 13 | } |
| 14 | |
| 15 | // if nums[i] is equal to the candidate, increase the count by 1 |
| 16 | if nums[i] == candidate { |
| 17 | count++ |
| 18 | } else { |
| 19 | // otherwise, decrease the count by 1 |
| 20 | count-- |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | // if there is a majority, it'll be in candidate because |
| 25 | // there will be more count++ than count-- for it. |
| 26 | return candidate |
| 27 | } |
no outgoing calls