LeetCode.S1450
题目:
题目大意:
如图所示。
数据范围:
startTime.length == endTime.length
1 <= startTime.length <= 100
1 <= startTime[i] <= endTime[i] <= 1000
1 <= queryTime <= 1000
思路:
使用差分数组(待更新)。更新start到end中的前缀和的值。我们在使f[start] += 1, f[end + 1] -= 1,相当于在f的前缀和数组s中start到end这个区间的值都加了1,而剩余区间的值不变。最后求一下f的前缀和数组s即可,则s[query]就是我们要求的值。
代码:
class Solution {
public int busyStudent(int[] startTime, int[] endTime, int queryTime) {
int[] f = new int[1010];
for (int i = 0; i < startTime.length; i ++ ){
f[startTime[i]] += 1;
f[endTime[i] + 1] -= 1;
}
for (int i = 1; i < 1010; i ++ ){
f[i] += f[i - 1];
}
return f[queryTime];
}
}
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();
int[] startTime = new int[]{9,8,7,6,5,4,3,2,1}, endTime = new int[]{10,10,10,10,10,10,10,10,10};
int queryTime = 5;
System.out.println(solution.busyStudent(startTime, endTime, queryTime));
}
}
时空复杂度分析等:
-
时间复杂度 : O(n)
-
空间复杂度 : O(n)