给你一个下标从 0 开始的二维整数数组
flowers,其中flowers[i] = [starti, endi]表示第i朵花的 花期 从starti到endi(都 包含)。同时给你一个下标从 0 开始大小为n的整数数组people,people[i]是第i个人来看花的时间。请你返回一个大小为
n的整数数组answer,其中answer[i]是第i个人到达时在花期内花的 数目 。
今天快乐 明天再补了 双节快乐~
思路
先遍历数组求出时间的最大值,然后求出flowers数组对应的差分数组【快速记录某个区间的变化量】,再将其转化为前缀和数组,得到每个时间点的开花数目
实现
class Solution {
public int[] fullBloomFlowers(int[][] flowers, int[] people) {
int max = Integer.MIN_VALUE;
for (int[] flower : flowers){
max = Math.max(flower[1], max);
}
for (int index : people){
max = Math.max(index, max);
}
int m = people.length;
int[] d = new int[max + 2];
int[] res = new int[m];
for (int[] flower : flowers){
int start = flower[0], end = flower[1];
d[start]++;
d[end + 1]--;
}
for (int i = 1; i <= max; i++){
d[i] += d[i - 1];
}
for (int i = 0; i < m; i++){
res[i] = d[people[i]];
}
return res;
}
}