ARTICLE AD BOX
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 5example 2:
2 5 3 1 1 5example 3:
1 5 2 5 3 1why is it random?
1
Explore related questions
See similar questions with these tags.
