URL: https://leetcode.com/problems/majority-element/ Signed-off-by: Matej Focko <me@mfocko.xyz>
29 lines
392 B
Go
29 lines
392 B
Go
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
|
|
}
|
|
}
|
|
}
|
|
}
|