核心思想
每个数-k
计算前缀和并放入map key=前缀和 value=当前下标
由于需要最长的子数组 所以只记录最先存在的下标
出现重复的前缀和 说明存在平均值为k的区间 [pre+1, i]
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
int a = in.nextInt();
int b = in.nextInt();
HashMap<Long,Integer> mp = new HashMap<>();
mp.put(0L, 0);
Long pre = 0L, cur = 0L;
int res = -1;
for(int i = 1; i <= a; i++){
cur = pre + in.nextInt() - b;
if(mp.containsKey(cur)){
res = Math.max(res, i - mp.get(cur));
}
else mp.put(cur, i);
pre = cur;
}
System.out.println(res);
}
}
标签:java,HashMap,真题,int,届秋招,util,0L,import,第三场
From: https://www.cnblogs.com/ganyq/p/18108961