先看题目
思路分析:
第一种方法就是暴力法,两个for循环,遍历,然后将预定数累加
暴力法比较费时,竟然没有报超时
还能进行优化,使用差分法的思想,将时间复杂度降到o(n)
看代码
class Solution {
public int[] corpFlightBookings(int[][] bookings, int n) {
int[] res = new int[n];
for (int i = 0; i < bookings.length; ++i) {
for (int j = bookings[i][0] - 1; j < bookings[i][1]; j++) {
res[j] += bookings[i][2];
}
}
return res;
}
}
class Solution {
public int[] corpFlightBookings(int[][] bookings, int n) {
int[] res = new int[n];
for(int[] booking : bookings) {
res[booking[0]-1] += booking[2];
if (booking[1] < n) {
res[booking[1]] -= booking[2];
}
}
for (int i = 1; i < n; i++) {
res[i] += res[i-1];
}
return res;
}
}
性能比暴力求解好很多,好了,今天先到这里