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);
}
}
}