I was solving a LeetCode question using Go language and i've used iteration over dict using this method:

package main import "fmt" func majorityElement(nums []int) int { m := make(map[int]int) for i:=0 ; i<len(nums) ; i++ { _, ok := m[nums[i]] if ok { m[nums[i]] += 1 } else { m[nums[i]] = 1 } } for key, val := range m { if val > len(nums)/2 { return key } } return 0 } func main() { arr := []int{3,2,3} fmt.Println(majorityElement(arr)) }

but the iteration over dict is random somehow, here i'll show few execution of this code (i've changed a bit for showing you the results):

for key, val := range m { fmt.Println(key, val) if val > len(nums)/2 { // return key } }

example 1:

3 1 1 5 2 5

example 2:

2 5 3 1 1 5

example 3:

1 5 2 5 3 1

why is it random?

assaabriiii's user avatar

1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.