摩尔投票法,O(n)的时间复杂度 public int majorityElement(int[] nums) { int num = 0; int count = 0; for(int n : nums){ if (count == 0) num = n; count = n == num ? ++count : --count; } return num; }
go语言版本 func majorityElement(nums []int) int { count, current := 0, 0 for _, v := range nums { if count == 0 { current = v count++ }else if(current == v) { count++ }else{ count-- } } return current }
func majorityElement(nums []int) int { hash_map := make(map[int]int) for i := 0; i < len(nums); i++ { hash_map[nums[i]]++ } key := 0 value := 0 for k, v := range hash_map { if v > value { key = k value = v } } return key }