053_多数元素
知识点:排序、哈希、摩尔投票
LeetCode第一百六十九题:https://leetcode-cn.com/problems/majority-element/submissions/
其中,排序的时空复杂度为O(nlogn), O(1),哈希为O(n), O(n), 摩尔投票为O(n), O(1)
语言:GoLang
// 哈希计数
func majorityElement(nums []int) int {
length := len(nums)
hMap := map[int]int{}
for _, v := range nums {
hMap[v]++
if hMap[v] > length / 2 {
return v
}
}
return 0
}
// 投票
func majorityElement__(nums []int) int {
length := len(nums)
cand, count := nums[0], 1
for i := 1; i < length; i++ {
if nums[i] == cand {
count++
} else {
if count == 0 {
cand, count = nums[i], 1
} else {
count--
}
}
}
return cand
}
// 排序,中位数即为答案
func majorityElement_(nums []int) int {
sort.Ints(nums)
return nums[len(nums) / 2]
}

浙公网安备 33010602011771号