forked from daattali/beautiful-jekyll
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ae076ee
commit ba4ab9a
Showing
1 changed file
with
67 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
# leetcode 2251 花期内花的数目(2023.9.28) | ||
## 题目 | ||
给你一个下标从 0 开始的二维整数数组 flowers ,其中 flowers[i] = [starti, endi] 表示第 i 朵花的 花期 从 starti 到 endi (都 包含)。同时给你一个下标从 0 开始大小为 n 的整数数组 people ,people[i] 是第 i 个人来看花的时间。 | ||
|
||
请你返回一个大小为 n 的整数数组 answer ,其中 answer[i]是第 i 个人到达时在花期内花的 数目 。 | ||
|
||
1 <= flowers.length <= 5 * 1e4 | ||
flowers[i].length == 2 | ||
1 <= starti <= endi <= 1e9 | ||
1 <= people.length <= 5 * 1e4 | ||
1 <= people[i] <= 1e9 | ||
## 题解 | ||
这道题乍一看就是差分+前缀和,实际上我写完提交了才发现,区间的范围最大值是1e9,所以得考虑离散化的方案。 | ||
|
||
感谢房宝给的解法:因为已经提前知道了查询的内容,所以可以做离线,简单来说就是开一个map用来代替差分数组,map记为presum,然后开始处理区间之前,先初始化presum[person[i]] = 0 | ||
接下来是走正常的差分流程。 | ||
presum[l]++ | ||
presum[r + 1]-- | ||
|
||
最后按照key的大小来排序,求前缀和。因为已经初始化了presum[person[i]] = 0,所以求完前缀和之后presum[person[i]]就是答案。 | ||
|
||
``` | ||
func fullBloomFlowers(flowers [][]int, people []int) []int { | ||
max := 0 | ||
for _, flower := range flowers { | ||
if flower[1] > max { | ||
max = flower[1] | ||
} | ||
} | ||
presum := make(map[int]int) | ||
for _, p := range people { | ||
presum[p] = 0 | ||
} | ||
for _, flow := range flowers { | ||
if _, ok := presum[flow[0]]; ok { | ||
presum[flow[0]]++ | ||
} else { | ||
presum[flow[0]] = 1 | ||
} | ||
if _, ok := presum[flow[1] + 1]; ok { | ||
presum[flow[1] + 1]-- | ||
} else { | ||
presum[flow[1] + 1] = -1 | ||
} | ||
} | ||
// fmt.Println(presum) | ||
keys := make([]int, 0) | ||
for k, _ := range presum { | ||
keys = append(keys, k) | ||
} | ||
sort.Ints(keys) | ||
for i := 1; i < len(keys); i++{ | ||
presum[keys[i]] = presum[keys[i]] + presum[keys[i - 1]] | ||
} | ||
// fmt.Println(presum) | ||
res := make([]int, 0) | ||
for _, p := range people { | ||
res = append(res, presum[p]) | ||
} | ||
return res | ||
} | ||
``` |