MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / majorityElement

Function majorityElement

majority_element_169/solution.go:5–27  ·  view source on GitHub ↗

Note: https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm Good problem and intro to a new algorithm.

(nums []int)

Source from the content-addressed store, hash-verified

3// Note: https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
4// Good problem and intro to a new algorithm.
5func 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}

Callers 1

Test_majorityElementFunction · 0.70

Calls

no outgoing calls

Tested by 1

Test_majorityElementFunction · 0.56