Skip to content

Commit

Permalink
add sol
Browse files Browse the repository at this point in the history
  • Loading branch information
ductnn committed Feb 12, 2024
1 parent 11d5bab commit 472394b
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions leetcode/169.MajorityElement/majorityElement.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// https://leetcode.com/problems/majority-element/

package main

import "fmt"

// Moore Voting Algo
func majorityElement(nums []int) int {
res := 0
cnt := 0

for _, num := range nums {
if cnt == 0 {
res = num
}
if num == res {
cnt++
} else {
cnt--
}
}

return res
}

// Hashmap
func majorityElement1(nums []int) int {
n := len(nums)
cnt := make(map[int]int)

for _, num := range nums {
cnt[num]++

if cnt[num] > n/2 {
return num
}
}

return -1
}

func main() {
nums := []int{2, 2, 2, 1, 1, 1, 2}
fmt.Println(majorityElement1(nums))
}

0 comments on commit 472394b

Please sign in to comment.