2020-8 / 18 El uso de estadísticas de contenedores-log

Título: Estadísticas de registro
Límite de tiempo: 1.0s Límite de memoria: 512.0MB
[Descripción del problema]
Xiao Ming mantiene un foro de programadores. Ahora ha recopilado un registro "Me gusta" con N líneas en total. El formato de cada línea es:
ts id
significa que la publicación con id numerada en el momento ts recibió un "me gusta".

Ahora Xiao Ming quiere contar qué publicaciones fueron alguna vez "publicaciones calientes". Si una publicación ha recibido no menos de K me gusta en cualquier período de tiempo de duración D, Xiao Ming piensa que la publicación fue una vez una "publicación caliente".
Específicamente, si hay un cierto momento T que satisface que la publicación reciba no menos de K me gusta durante el período de [T, T + D) (tenga en cuenta que la izquierda está cerrada y la derecha está abierta), la publicación estuvo una vez "caliente Enviar".

Dado un registro, ayude a Xiao Ming a contar todos los números de publicaciones que alguna vez fueron "publicaciones calientes".
[Formato de entrada] La
primera línea contiene tres números enteros N, D y K.
Las siguientes N líneas, un registro por línea, contienen dos enteros ts e id.

Para el 50% de los datos, 1 <= K <= N <= 1000
Para el 100% de los datos, 1 <= K <= N <= 100000 0 <= ts <= 100000 0 <= id <= 100000

[Formato de salida]
Salida ID de publicación activa en orden descendente. Una línea por id.

[Ejemplo de entrada]
7 10 2
0 1
0 10
10 10
10 1
9
1100
3100 3

【Salida de muestra】
1
3

Idea general: esta pregunta necesita registrar el tiempo de los me gusta, la identificación de los me gusta y cuántos me gusta se obtienen. Primero, use un subíndice de matriz para indicar la hora, luego instale una ArrayList en la matriz y cargue la identificación de los similares en ArrayList. , Y luego defina un HashMap, la clave es la identificación del me gusta, el valor es la cantidad de Me gusta, y luego coloque la identificación que cumpla con el significado de la pregunta en el HashSet (HashSet se des-duplica automáticamente para evitar que una identificación aparezca varias veces) y luego coloque el HashSet Ingrese una LinkedList y ordene por id. el código se muestra a continuación

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;
public class A日志统计 {
    
    
	public static ArrayList<Integer>[] arr=new ArrayList[100000];
	public static void Init(){
    
    
		for(int i=0;i<arr.length;i++){
    
    
			arr[i]=new ArrayList<Integer>();
		}
	}
	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int D = sc.nextInt();
		int K = sc.nextInt();
		Init();
		HashMap<Integer,Integer>map = new HashMap<Integer,Integer>();
		HashSet<Integer>set = new HashSet<Integer>();
		LinkedList<Integer>list = new LinkedList<Integer>();
		for(int i=0;i<N;i++) {
    
    
			int ts = sc.nextInt();
			int id = sc.nextInt();
			arr[ts].add(id);
		}//下标代表时间,容器内装的是id
		long bt = System.currentTimeMillis();
		for(int i=0;i<arr.length;i++) {
    
    //遍历数组
			if(i>=D) {
    
    //出口
				//对D内容器进行遍历
				for(int t:arr[i-D]) {
    
    //遍历容器,得到点赞次数
					if(map.get(t)>=K) {
    
    
			//如果点赞次数满足要求,则放入HashSet中
						set.add(t);//Set自动去重
					}
			//这里将第一个点赞次数-1,相当于做了一个移出操作,然后移入下一个时间
					map.put(t, map.get(t)-1);
				}
			}
			//先将map里边传值
			for(int t:arr[i]) {
    
    //遍历容器,将容器内东西传给map
				//key为帖子id,也就是容器内的值,value为点赞次数
				if(map.containsKey(t)) {
    
    
					//作比较,如果有关键字t,点赞次数+1
					map.put(t,map.get(t)+1);
				}else {
    
    
					//如果没有关键字t,点赞次数初始化为1
					map.put(t,1);
				}
			}
		}
		for(int t:set) {
    
    
			list.add(t);
	//因为set不能排序,所以转换成ArrayList或者LinkedList排序
		}
		Collections.sort(list);//按照id排序
		for(int t:list) {
    
    
			System.out.println(t);
		}
//记录一下运行时间,看是否超时
		long et = System.currentTimeMillis();
		System.out.println(et-bt);
	}
}

Si el jefe tiene una mejor forma de escribir, avise

Supongo que te gusta

Origin blog.csdn.net/weixin_45956597/article/details/108092447
Recomendado
Clasificación