leetcode之哈希表七: 无人机方阵

原题:

力扣icon-default.png?t=LBL2https://leetcode-cn.com/problems/0jQkd0/

一、题目要求

在 「力扣挑战赛」 开幕式的压轴节目 「无人机方阵」中,每一架无人机展示一种灯光颜色。 无人机方阵通过两种操作进行颜色图案变换:

调整无人机的位置布局
切换无人机展示的灯光颜色
给定两个大小均为 N*M 的二维数组 source 和 target 表示无人机方阵表演的两种颜色图案,由于无人机切换灯光颜色的耗能很大,请返回从 source 到 target 最少需要多少架无人机切换灯光颜色。

注意: 调整无人机的位置布局时无人机的位置可以随意变动。

示例 1:

输入:source = [[1,3],[5,4]], target = [[3,1],[6,5]]

输出:1

解释:
最佳方案为
将 [0,1] 处的无人机移动至 [0,0] 处;
将 [0,0] 处的无人机移动至 [0,1] 处;
将 [1,0] 处的无人机移动至 [1,1] 处;
将 [1,1] 处的无人机移动至 [1,0] 处,其灯光颜色切换为颜色编号为 6 的灯光;
因此从source 到 target 所需要的最少灯光切换次数为 1。

8819ccdd664e91c78cde3bba3c701986.gif

 

示例 2:

输入:source = [[1,2,3],[3,4,5]], target = [[1,3,5],[2,3,4]]

输出:0
解释:
仅需调整无人机的位置布局,便可完成图案切换。因此不需要无人机切换颜色

提示:
n == source.length == target.length
m == source[i].length == target[i].length
1 <= n, m <=100
1 <= source[i][j], target[i][j] <=10^4

二、解题

package com.leetcode.hash;

import java.util.HashMap;

public class Solution19 {
    public static void main(String[] args) {
        int[][] source = {{1,3},{5,4}}, target = {{3,1},{6,5}};
        System.out.println(minimumSwitchingTimes(source, target));
    }


    public static int minimumSwitchingTimes(int[][] source, int[][] target) {
        int n = source.length;
        int m = source[0].length;
        HashMap<Integer, Integer> map1 = new HashMap<Integer, Integer>();
        HashMap<Integer, Integer> map2 = new HashMap<Integer, Integer>();

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                int s = source[i][j];
                int t = target[i][j];

                if (map1.containsKey(s)) {
                    map1.put(s, map1.get(s) + 1);
                } else {
                    map1.put(s, 1);
                }

                if (map2.containsKey(t)) {
                    map2.put(t, map2.get(t) + 1);
                } else {
                    map2.put(t, 1);
                }
            }
        }

        int count = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                int t = target[i][j];
                if (map1.containsKey(t) && map1.get(t) > 0) {
                    map1.put(t, map1.get(t) - 1);
                } else {
                    count++;
                }
            }
        }

        return count;
    }
}

三、运行结果

四、提交结果

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值