题目 |
难度 |
要点 |
拼车 |
● |
不需要构造原始数组,直接判断即可 |
航班预定统计 |
● |
构造原始数组 |
区间加法 |
● |
构造原始数组 |
| 差分数组中,diff[i] 就是 nums[i] 和 nums[i-1] 之差 |
拼车
| class Solution { |
| |
| public boolean carPooling(int[][] trips, int capacity) { |
| Diff diff = new Diff(1001); |
| for (int[] trip: trips) { |
| diff.inc(trip[0], trip[1], trip[2]); |
| } |
| return diff.check(capacity); |
| } |
| |
| } |
| |
| class Diff { |
| |
| private int size; |
| |
| private int[] diff; |
| |
| public Diff(int size) { |
| this.size = size; |
| this.diff = new int[size]; |
| } |
| |
| public void inc(int val, int start, int end) { |
| diff[start] += val; |
| diff[end] -= val; |
| } |
| |
| public boolean check(int capacity) { |
| int sum = diff[0]; |
| for (int i = 1; i < diff.length; i++) { |
| if (sum > capacity) { |
| return false; |
| } |
| sum += diff[i]; |
| } |
| return sum <= capacity; |
| } |
| |
| } |
航班预定统计
| class Solution { |
| public int[] corpFlightBookings(int[][] bookings, int n) { |
| Diff diff = new Diff(n); |
| for (int[] booking: bookings) { |
| diff.inc(booking[2], booking[0] - 1, booking[1] - 1); |
| } |
| return diff.revert(); |
| } |
| } |
| |
| |
| class Diff { |
| |
| private int size; |
| |
| private int[] diff; |
| |
| public Diff(int size) { |
| this.size = size; |
| this.diff = new int[size]; |
| } |
| |
| public void inc(int val, int start, int end) { |
| diff[start] += val; |
| if (end + 1 < diff.length) { |
| diff[end + 1] -= val; |
| } |
| } |
| |
| public int[] revert() { |
| int[] sum = new int[diff.length]; |
| sum[0] = diff[0]; |
| for (int i = 1; i < diff.length; i++) { |
| sum[i] = sum[i - 1] + diff[i]; |
| } |
| return sum; |
| } |
| } |
区间加法
| class Solution { |
| public int[] getModifiedArray(int length, int[][] updates) { |
| Diff diff = new Diff(length); |
| for (int[] update: updates) { |
| diff.inc(update[0], update[1], update[2]); |
| } |
| return diff.revert(); |
| } |
| } |
| |
| class Diff { |
| |
| private int size; |
| |
| private int[] diff; |
| |
| public Diff(int size) { |
| this.size = size; |
| this.diff = new int[size]; |
| } |
| |
| public void inc(int start, int end, int val) { |
| diff[start] += val; |
| if (end + 1 < diff.length) { |
| diff[end + 1] -= val; |
| } |
| } |
| |
| public int[] revert() { |
| int[] sum = new int[diff.length]; |
| sum[0] = diff[0]; |
| for (int i = 1; i < diff.length; i++) { |
| sum[i] = sum[i - 1] + diff[i]; |
| } |
| return sum; |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义