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:
Matej Focko 2025-01-03 14:26:45 +01:00
parent 4204acb546
commit 3285c5515e
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

29
go/majority-element.go Normal file
View 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
}
}
}
}