给定一个乱序的数组,删除所有的重复元素,使得每个元素只出现一次,并且按照出现的次数从高到低进行排序,相同出现次数按照第一次出现顺序进行先后排序
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
"strings"
)
type intCount struct {
key int
count int
}
func getIndexByValue(list []int, value int) int {
for i, i2 := range list {
if i2 == value {
return i
}
}
return -1
}
func main() {
var inputStr string
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
inputStr = scanner.Text()
}
strList := strings.Split(inputStr, ",")
intList := make([]int, len(strList))
for i, s := range strList {
intList[i], _ = strconv.Atoi(s)
}
intDistinctList := make(map[int]int)
for _, s := range intList {
intDistinctList[s]++
}
intCountList := make([]*intCount, 0)
for c, i := range intDistinctList {
intCountList = append(intCountList, &intCount{
key: c,
count: i,
})
}
sort.Slice(intCountList, func(i, j int) bool {
if intCountList[i].count != intCountList[j].count {
return intCountList[i].count > intCountList[j].count
}
return getIndexByValue(intList, intCountList[i].key) < getIndexByValue(intList, intCountList[j].key)
})
outputStr := ""
for _, item := range intCountList {
if outputStr == "" {
outputStr = fmt.Sprintf("%d", item.key)
} else {
outputStr = fmt.Sprintf("%s,%d", outputStr, item.key)
}
}
fmt.Println(outputStr)
}
这道题和前面做过的“字符统计及重排”类型一致,解法也相同,属于比较简单的题目