算法93---修改矩阵

一、题目:修改矩阵(美团2019春招实习笔试)

思路:采用两个矩阵存储这两个不同的数字

代码:

from collections import Counter

n, m = input().split()
n, m = int(n), int(m)
arr = []
for i in range(n):
    arr.append(list(map(int, input().split())))


def bwMatrix(arr, n, m):
    res = 0
    one, two = [], []
    for i in range(n):
        for j in range(m):
            if (i + j) & 1:
                one.append(arr[i][j])
            else:
                two.append(arr[i][j])
    dicone = Counter(one)
    dictwo = Counter(two)
    sort_one = sorted(dicone.items(), key=lambda x: x[1], reverse=True)
    sort_two = sorted(dictwo.items(), key=lambda x: x[1], reverse=True)
    
    sort_one.append([float('inf'),0])
    sort_two.append([-float('inf'),0])
    ##如果one中最多的数和two中最多的数不等
    if sort_one[0][0] != sort_two[0][0]:
        return (len(one) - sort_one[0][1]) + (len(two) - sort_two[0][1])
    ##如果相等,分三种情况,最多数的个数不等(one多、two多),最多数的个数相等(比较第二多数的个数大小)。
    else:
        if sort_one[0][1] > sort_two[0][1]:
            return (len(two) - sort_two[1][1]) + (len(one) - sort_one[0][1])
        elif sort_one[0][1] < sort_two[0][1]:
            return (len(one) - sort_one[1][1]) + (len(two) - sort_two[0][1])
        else:
            if sort_one[1][1] >= sort_two[1][1]:
                return (len(two) - sort_two[0][1]) + (len(one) - sort_one[1][1])
            else:
                return (len(two) - sort_two[1][1]) + (len(one) - sort_one[0][1])


print(bwMatrix(arr, n, m))
# 3 3
# 1 1 1
# 1 5 1
# 1 1 1
原文地址:https://www.cnblogs.com/Lee-yl/p/10760424.html