花期内花的数目【LC2251】
给你一个下标从 0 开始的二维整数数组
flowers,其中flowers[i] = [starti, endi]表示第i朵花的 花期 从starti到endi(都 包含)。同时给你一个下标从 0 开始大小为n的整数数组people,people[i]是第i个人来看花的时间。请你返回一个大小为
n的整数数组answer,其中answer[i]是第i个人到达时在花期内花的 数目 。
今天快乐 明天再补了 双节快乐~
普通差分【MLE】
-
思路
先遍历数组求出时间的最大值,然后求出
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; } }
花期内花的数目问题的解法

博客围绕‘花期内花的数目【LC2251】’问题展开,给出一个二维整数数组表示花的花期,一个整数数组表示人看花的时间,需返回每个人到达时花期内花的数目。介绍了普通差分(会出现 MLE)、差分 + 哈希表 + 离线查询(排序)、二分查找等解法。

6万+

被折叠的 条评论
为什么被折叠?



