老规矩,先挂上参考文章
力扣1109.航班预订信息
输入:bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
输出:[10,55,45,25,25]
解释:
航班编号 1 2 3 4 5
预订记录 1 : 10 10
预订记录 2 : 20 20
预订记录 3 : 25 25 25 25
总座位数: 10 55 45 25 25
因此,answer = [10,55,45,25,25]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/corporate-flight-bookings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目就是这样式的 完整题目可以去力扣去看
我使用暴力解法,可以实现并且没有超时
var corpFlightBookings = function(bookings, n) {
let answer =Array(n).fill(0)
bookings.map((item)=>{
for(let i = item[0];i<=item[1];i++){
// answer[i-1] = 0+item[2];
// if(answer[i-1] !== 0){
answer[i-1] = answer[i-1]+item[2];
// }
}
})
return answer;
};
然后看了官方解法,学会差分数组,简单方便
差分数组原理:
附上实现代码
var corpFlightBookings = function(bookings, n) {
let answer =Array(n).fill(0);
//新建一个数组,这个数组的差分数组和自身长得一样
//[0,0,0,0,0,0]的差分数组就是[0,0,0,0,0,0]
for(const item of bookings){
answer[item[0]-1] += item[2];
if (item[1] < n) {
answer[item[1]] -= item[2];
}
}
//对差分数组进行一系列操作之后,得到一个最后的差分数组
//再得到最终的数组
for(let i = 1;i<n;i++){
answer[i] += answer[i-1]
}
return answer
};
查分数组用途:
1.对数组中的一些数进行指定数值的增加或减少
2.频繁的对数组中一部分数进行操作