# 请听第二道算法题：修改矩阵

image

package main

import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
"strings"
)

type pair struct {
num int
cnt int
}

type PairList []pair

func (p PairList) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p PairList) Len() int           { return len(p) }
func (p PairList) Less(i, j int) bool { return p[i].cnt > p[j].cnt }

func main() {
nm = strings.Trim(nm, "\r\n")
n, _ := strconv.Atoi(strings.Split(nm, " ")[0])
m, _ := strconv.Atoi(strings.Split(nm, " ")[1])
odde := make(map[int]int) //统计奇数格子上各数字出现的次数
evene := make(map[int]int)//统计偶数格子上各数字出现的次数
for i := 0; i < n; i++ {
str = strings.Trim(str, "\r\n")
line := strings.Split(str, " ")

for j := 0; j < m; j++ {
e, _ := strconv.Atoi(line[j])
if (i+j)%2 == 0 {
cnt, ok := odde[e]
if !ok {
odde[e] = 1
} else {
odde[e] = cnt + 1
}
} else {
cnt, ok := evene[e]
if !ok {
evene[e] = 1
} else {
evene[e] = cnt + 1
}
}
}
}
oddlist := make(PairList, 0, len(odde))
for n, c := range odde {
oddlist = append(oddlist, pair{n, c}) // 将map中的kv对封装成pair结构体，用于排序
}
sort.Sort(oddlist)
if len(oddlist) == 1 {
oddlist = append(oddlist, pair{-1, 0})
}

evenlist := make(PairList, 0, len(evene))
for n, c := range evene {
evenlist = append(evenlist, pair{n, c})
}
sort.Sort(evenlist)
if len(evenlist) == 1 {
evenlist = append(evenlist, pair{-1, 0})
}

var retained int // 保留的数字数量，取最大
for i := 0; i < 2; i++ {
for j := 0; j  b {
return a
} else {
return b
}
}

image