• 华为OD机试真题【最多颜色的车辆】


    1、题目描述

    【最多颜色的车辆】

    【题目描述】
    在一个狭小的路口,每秒只能通过一辆车,假好车辆的颜色只有 3 种,找出 N 秒内经过的最多颜色的车辆数量。
    三种颜色编号为0 ,1 ,2

    【输入描述】
    第一行输入的是通过的车辆颜色信息
    [0,1,1,2] 代表4 秒钟通过的车辆颜色分别是 0 , 1 , 1 , 2
    第二行输入的是统计时间窗,整型,单位为秒

    【输出描述】
    输出指定时间窗内经过的最多颜色的车辆数量。

    【示例1】
    输入:
    0 1 2 1
    3

    输出:
    2
    样例解释
    在 3 秒时间窗内,每个颜色最多出现 2 次。例如:[1,2,1]

    【示例2】
    输入:
    0 1 2 1
    2

    输出:
    1
    样例解释
    在 2 秒时间窗内,每个颜色最多出现1 次。

    2、解题思路

    该题运用滑动窗口的思想,用Map来统计来统计每个颜色的出现的次数,在指定窗口数量内出现最大的次数。

    3、参考代码

    import java.util.Collection;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Scanner;
    
    
    public class 最多颜色的车辆 {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            while (in.hasNext()) {
                String str = in.nextLine();
                int num = Integer.parseInt(in.nextLine());
    
                String[] arr = str.split(" ");
    
                if (arr.length < num) {
                    continue;
                }
    
                Map<String, Integer> map = new HashMap<>();
    
                int left = 0;
                int max = 0;
                for (int right = 0; right < arr.length; right++) {
                    if (right >= num) {
                        if (map.containsKey(arr[left]) && map.get(arr[left]) > 0) {
                            map.put(arr[left], map.get(arr[left]) - 1);
                        }
                        Collection<Integer> values = map.values();
                        max = Math.max(max, Collections.max(values));
                    }
                    map.put(arr[right], map.getOrDefault(arr[right], 0) + 1);
                }
    
                System.out.println(max);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    4、相似题目

  • 相关阅读:
    基于STM32+华为云设计的智能鱼缸
    MySQL之DML操作
    MySQL34道例题
    Dockershim 与 Containerd:两种容器运行时的故事
    uniapp登录页面( 适配:pc、小程序、h5)
    初识Protobuf
    Rabbit加密算法:性能与安全的完美结合
    【SSR服务端渲染+CSR客户端渲染+post请求+get请求+总结】三种开启服务器的方法总结
    基于机器视觉的火车票识别系统 计算机竞赛
    mysql忘记密码无法登录
  • 原文地址:https://blog.csdn.net/weixin_43763430/article/details/130816962