go: add «169. Majority Element»
URL: https://leetcode.com/problems/majority-element/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
4204acb546
commit
3285c5515e
1 changed files with 29 additions and 0 deletions
29
go/majority-element.go
Normal file
29
go/majority-element.go
Normal file
|
@ -0,0 +1,29 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
rand "math/rand/v2"
|
||||
)
|
||||
|
||||
func majorityElement(nums []int) int {
|
||||
DISCARD := -1_000_000_001
|
||||
|
||||
threshold := len(nums) >> 1
|
||||
for {
|
||||
sample := nums[rand.N(len(nums))]
|
||||
if sample == DISCARD {
|
||||
continue
|
||||
}
|
||||
|
||||
counter := 0
|
||||
for i, x := range nums {
|
||||
if x == sample {
|
||||
counter++
|
||||
nums[i] = DISCARD
|
||||
}
|
||||
|
||||
if counter > threshold {
|
||||
return sample
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue