Golang中如何找出数组中出现频率最高且数值最大的元素
Golang中如何找出数组中出现频率最高且数值最大的元素
func HighestRank(a []int) int{
count :=1
var tempCount int
var popular int =a[0]
var temp int = 0
for i := 0; i < len(a); i++{
temp = a[i]// holding the current element at each iteration
tempCount = 0//this is maintain for counting the frequency of each elements so must be start from zero
for j := 1; j < len(a); j++{
if (temp == a[j]){//counting the frequencies
tempCount = (tempCount +1) }
}
if (tempCount > count){// current element count is greater than the previous holding value of count
popular = temp//then have current element into popular
count = tempCount//make highest frequencies as count upto
}
}
return popular
}
func main() {
arr := []int{30 ,30, 10, 10, 20, 20}//output 30
ret := HighestRank(arr)
fmt.Println(ret)
}
更多关于Golang中如何找出数组中出现频率最高且数值最大的元素的实战教程也可以访问 https://www.itying.com/category-94-b0.html
3 回复
你的代码问题在于没有检查 temp 和 popular 的出现频率是否相同。
我做了一些修改(同时返回该数字的出现频率)
func HighestRank(a []int) (int, int) {
popular, count := a[0], 1
for i := 0; i < len(a); i++ {
temp, tempCount := a[i], 1
for j := i + 1; j < len(a); j++{
if (temp == a[j]){
tempCount++
}
}
if (tempCount > count || (tempCount == count && temp > popular)){
popular = temp
count = tempCount
}
}
return popular, count
}
这是一个典型的统计频率并比较的问题。你当前的代码存在几个问题:
- 时间复杂度高:使用了嵌套循环,时间复杂度为 O(n²)
- 逻辑错误:内层循环从 j=1 开始,会漏掉第一个元素的比较
- 没有处理频率相同的情况:题目要求"频率最高且数值最大",当前代码只考虑了频率
以下是改进的实现:
package main
import "fmt"
func HighestRank(a []int) int {
if len(a) == 0 {
return 0
}
// 使用map统计频率
freq := make(map[int]int)
for _, num := range a {
freq[num]++
}
// 找出频率最高且数值最大的元素
maxFreq := 0
result := a[0]
for num, count := range freq {
if count > maxFreq || (count == maxFreq && num > result) {
maxFreq = count
result = num
}
}
return result
}
func main() {
// 测试用例
tests := []struct {
arr []int
expected int
}{
{[]int{30, 30, 10, 10, 20, 20}, 30}, // 频率相同(2次),30最大
{[]int{12, 10, 8, 12, 7, 6, 4, 10, 12}, 12}, // 12出现3次,频率最高
{[]int{5, 5, 5, 2, 2, 2, 1, 1, 1}, 5}, // 频率相同(3次),5最大
{[]int{1, 2, 3, 4, 5}, 5}, // 所有元素频率相同(1次),5最大
}
for _, test := range tests {
result := HighestRank(test.arr)
fmt.Printf("arr: %v, result: %d, expected: %d, correct: %v\n",
test.arr, result, test.expected, result == test.expected)
}
}
更简洁的写法:
func HighestRank(a []int) int {
freq := make(map[int]int)
for _, v := range a {
freq[v]++
}
maxFreq, maxNum := 0, 0
for num, count := range freq {
if count > maxFreq || (count == maxFreq && num > maxNum) {
maxFreq = count
maxNum = num
}
}
return maxNum
}
这个实现:
- 时间复杂度:O(n),只需要遍历数组两次
- 空间复杂度:O(n),使用map存储频率
- 正确处理了频率相同的情况,选择数值更大的元素
- 代码更简洁易读

