当前位置: 首页 > java >正文

差分数组算法

详情

1094. 拼车
class Solution {public boolean carPooling(int[][] trips, int capacity) {TreeMap<Integer, Integer> diff = new TreeMap<>();for (int[] trip : trips) {int num = trip[0], from = trip[1], to = trip[2];diff.merge(from, num, Integer::sum);diff.merge(to, -num, Integer::sum);}int sum = 0;for (int v: diff.values()) {sum += v;if (sum > capacity) {return false;}}return true;}
}
1109. 航班预订统计
class Solution {public int[] corpFlightBookings(int[][] bookings, int n) {int[] res = new int[n + 1]; // 离开在后一个离开for (int[] booking : bookings) {int first = booking[0], last = booking[1], seat = booking[2];res[first - 1] += seat;res[last] -= seat;}for (int i = 1; i < n; i++) {res[i] += res[i - 1];}int[] ans = new int[n];System.arraycopy(res, 0, ans, 0, n);return ans;}
}
121. 买卖股票的最佳时机
class Solution {public int maxProfit(int[] prices) {int res = 0;int minPrice = prices[0];for (int price : prices) {res = Math.max(res, price - minPrice);  // 计算minPrice = Math.min(minPrice, price);   // 维护左边出现的最小价格}return res;}
}
122. 买卖股票的最佳时机 II
class Solution {public int maxProfit(int[] prices) {int n = prices.length;int[] diff = new int[n];diff[0] = prices[0];int res = 0;for (int i = 1; i < n; i++) {diff[i] = prices[i] - prices[i - 1];res += Math.max(diff[i], 0);}return res;}
}
253. 会议室II

给定一个会议时间安排的数组,每个会议时间都会包括开始和结束的时间 [[s1,e1],[s2,e2],...](si<ei)[[s_1,e_1],[s_2,e_2],...] (s_i < e_i)[[s1,e1],[s2,e2],...](si<ei), 为避免会议冲突,同时要考虑充分利用会议室资源,请你计算至少需要多少间会议室,才能满足这些会议安排。

示例 1:
输入: [[0, 30],[5, 10],[15, 20]]
输出: 2示例 2:
输入: [[7,10],[2,4]]
输出: 1
public class Solution {int minMeetingRooms(int[][] intervals) {int n = 10001;int[] diff = new int[n];for (int[] interval : intervals) {int start = interval[0], end = interval[1];diff[start] += 1;diff[end] -= 1;}int res = 0;for (int i = 1; i < n; i++) {diff[i] = diff[i - 1] + diff[i];res = Math.max(res, diff[i]);}return res;}
}
http://www.xdnf.cn/news/15686.html

相关文章:

  • [simdjson] 填充字符串 | `document` 对象 | on-demand 模式
  • C++并发编程-14. 利用栅栏实现同步
  • Redis学习其三(订阅发布,主从复制,哨兵模式)
  • Windows 安装WSL +Docker 部署通义千问大模型(同步解决Ubuntu启动命令闪退)
  • 图片平铺下去总是有个缝隙的解决方案
  • Vue常见指令
  • 【解码文本世界的“隐形分界线”:Windows与Linux回车换行之谜】
  • Python网络爬虫之selenium库
  • coredns使用etcd
  • Gitee 远程库多人如何协作?
  • CCF编程能力等级认证GESP—C++1级—20250628
  • QT窗口(4)-浮动窗口
  • Kotlin封装
  • 萤石摄像头C++SDK应用实例
  • 微信小程序 wx.request() 的封装
  • Github库镜像到本地私有Gitlab服务器
  • PortSwigger Labs 之 点击劫持利用
  • RPC 与 Feign 的区别笔记
  • Spring AI开发智能客服(Tool calling)
  • 开启modbus tcp模拟调试
  • 【LeetCode 热题 100】199. 二叉树的右视图——(解法一)BFS
  • 自己动手实现 strlen:从循环到递归的四种写法
  • Postman/Apipost中使用Post URL编码发送含换行符参数的问题分析
  • 现代R语言机器学习:Tidymodel/Tidyverse语法+回归/树模型/集成学习/SVM/深度学习/降维/聚类分类与科研绘图可视化
  • 串口(Serial Port)是什么?
  • 在 React 中根据数值动态设置 SVG 线条粗细
  • 【52】MFC入门到精通——MFC串口助手(二)---通信版(发送数据 、发送文件、数据转换、清空发送区、打开/关闭文件),附源码
  • 9. isaacsim4.2教程-ROS加相机/CLOCK
  • vs openssl编译提示无法打开文件“libssl.lib”或“libcrypto.lib”
  • 回归预测 | MATLAB实现SA-BP模拟退火算法优化BP神经网络多输入单输出回归预测