★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-tlnrxiqv-ky.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
There are n
flights, and they are labeled from 1
to n
.git
We have a list of flight bookings. The i
-th booking bookings[i] = [i, j, k]
means that we booked k
seats from flights labeled i
to j
inclusive.github
Return an array answer
of length n
, representing the number of seats booked on each flight in order of their label. 數組
Example 1:微信
Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5 Output: [10,55,45,25,25]
Constraints:app
1 <= bookings.length <= 20000
1 <= bookings[i][0] <= bookings[i][1] <= n <= 20000
1 <= bookings[i][2] <= 10000
這裏有 n
個航班,它們分別從 1
到 n
進行編號。spa
咱們這兒有一份航班預訂表,表中第 i
條預訂記錄 bookings[i] = [i, j, k]
意味着咱們在從 i
到 j
的每一個航班上預訂了 k
個座位。code
請你返回一個長度爲 n
的數組 answer
,按航班編號順序返回每一個航班上預訂的座位數。 htm
示例:blog
輸入:bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5 輸出:[10,55,45,25,25]
提示:
1 <= bookings.length <= 20000
1 <= bookings[i][0] <= bookings[i][1] <= n <= 20000
1 <= bookings[i][2] <= 10000
1 class Solution { 2 func corpFlightBookings(_ bookings: [[Int]], _ n: Int) -> [Int] { 3 var solution = Array(repeating: 0, count: n) 4 5 for booking in bookings { 6 solution[booking[0]-1] += booking[2] 7 if booking[1] < n { solution[booking[1]] -= booking[2] } 8 } 9 10 for i in 1..<n { 11 solution[i] += solution[i-1] 12 } 13 14 return solution 15 } 16 }
1240ms
1 class Solution { 2 func corpFlightBookings(_ bookings: [[Int]], _ n: Int) -> [Int] { 3 var diff = [Int](repeating: 0, count: n+1) 4 for book in bookings { 5 let start = book[0] 6 let end = book[1] 7 let count = book[2] 8 diff[start-1] += count 9 diff[end] -= count 10 } 11 12 var result = [Int](repeating: 0, count: n) 13 for i in 0..<n { 14 result[i] = (i - 1 >= 0 ? result[i-1] : 0) + diff[i] 15 } 16 return result 17 } 18 }
1312ms
1 class Solution { 2 func corpFlightBookings(_ bookings: [[Int]], _ n: Int) -> [Int] { 3 var line = [Int](repeating: 0, count: n + 2) 4 for b in bookings { 5 line[b[0]] += b[2] 6 line[b[1] + 1] -= b[2] 7 } 8 var res = [Int]() 9 var r = 0 10 for i in 1...n { 11 r += line[i] 12 res.append(r) 13 } 14 return res 15 } 16 }
Runtime: 1336 ms
1 class Solution { 2 func corpFlightBookings(_ bookings: [[Int]], _ n: Int) -> [Int] { 3 var res:[Int] = [Int](repeating:0,count:n) 4 for b in bookings 5 { 6 res[b[0] - 1] += b[2] 7 if b[1] < n 8 { 9 res[b[1]] -= b[2] 10 } 11 } 12 13 for i in 1..<n 14 { 15 res[i] += res[i - 1] 16 } 17 return res 18 } 19 }