美团java在线笔试题_美团点评春招在线笔试后台开发方向笔试题编程题第一题题解...

该博客主要介绍了如何解决一道关于Java在线笔试的问题,即给定一个矩阵,计算最少需要修改多少元素才能使其成为黑白矩阵。通过读取输入,使用HashMap存储不同位置的数值及其出现次数,然后比较并计算得出最少修改次数。
摘要由CSDN通过智能技术生成

题目概述:

定义一个矩阵为黑白矩阵,当且仅当对于矩阵内的任意一个元素,其上下左右的数字完全一致(如果存在)且不和本身重复

现给出一个矩阵A,给定大小为n*m,内部数据都为整型,请问至少修改矩阵中的几个元素才能使得矩阵A为黑白矩阵?

输入描述:

第一行:n m

之后n行,每行有m个整数,用空格分割

输出描述:

一个整数

输入样例:

3 3

1 1 1

1 1 1

1 1 1

输出样例:

4

输入样例2:

3 3

1 1 1

1 5 1

1 1 1

输出样例2:

4

输入样例3:

3 4

1 2 3 1

2 3 1 2

3 1 2 3

输出样例3:

6

import java.util.*;

public class TestMain {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

int m = sc.nextInt();

Map map0 = new HashMap<>();

Map map1 = new HashMap<>();

int[][] arr = new int[n][m];

for(int i = 0; i

for(int j = 0;j

arr[i][j]= sc.nextInt();

}

}

for(int i = 0; i

for(int j = 0;j

int target = arr[i][j];

if((i+j)%2==0){

int count = 1;

if(map0.get(target)!=null){

count = map0.get(target)+1;

}else{

}

map0.put(target,count);

}else{

int count = 1;

if(map1.get(target)!=null){

count = map1.get(target)+1;

}else{

}

map1.put(target,count);

}

}

}

List list = new ArrayList<>();

for(Map.Entry entry:map0.entrySet()){

Topnum topnum = new Topnum();

topnum.setKey(entry.getKey());

topnum.setValue(entry.getValue());

list.add(topnum);

}

list.sort(Comparator.comparingInt(Topnum::getValue));

List list1 = new ArrayList<>();

for(Map.Entry entry:map1.entrySet()){

Topnum topnum = new Topnum();

topnum.setKey(entry.getKey());

topnum.setValue(entry.getValue());

list1.add(topnum);

}

list1.sort(Comparator.comparingInt(Topnum::getValue));

if(list.get(list.size()-1).getKey().equals(list1.get(list1.size()-1).getKey())){

int left = 0;

int right = 0;

if(list1.size()>1){

left = (m*n+1)/2-list.get(list.size()-1).getValue()+(m*n)/2-list1.get(list1.size()-2).getValue();

}else{

left = (m*n+1)/2-list.get(list.size()-1).getValue()+(m*n)/2;

}

if(list.size()>1){

right = (m*n+1)/2-list.get(list.size()-2).getValue()+(m*n)/2-list1.get(list1.size()-1).getValue();

}else{

right = (m*n+1)/2+(m*n)/2-list1.get(list1.size()-1).getValue();

}

System.out.println(left>right?right:left);

}else{

int ret1 = (m*n+1)/2-list.get(list.size()-1).getValue()+(m*n)/2-list1.get(list1.size()-1).getValue();

System.out.println(ret1);

}

}

}

class Topnum {

private Integer key;

private Integer value;

public Integer getKey() {

return key;

}

public Integer getValue() {

return value;

}

public void setKey(Integer key) {

this.key = key;

}

public void setValue(Integer value) {

this.value = value;

}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值