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

【18. 四数之和 】

Leetcode算法练习 笔记记录

  • 18. 四数之和

18. 四数之和

这题其实和三数之和差不多,相当于同一个板子,具体可以看-> 三数之和或者看灵神讲解b站灵神讲解

 public List<List<Integer>> fourSum(int[] nums, int target) {int n = nums.length;Arrays.sort(nums);List<List<Integer>> ans = new ArrayList<>();for (int i = 0; i < n - 3; i++) {//枚举第一个数long x=nums[i];//跳过重复的数if (i > 0 && x == nums[i - 1]) {continue;}//优化1 最小的数都比target大,说明没有目标数组if (x+nums[i+1]+nums[i+2]+nums[i+3]>target){break;}//优化2 加上任意3个数都比目标值小,说明当前x不够大跳过本次if(x+nums[n-3]+nums[n-2]+nums[n-1]<target){continue;}//枚举第二个数for (int j = i + 1; j < n - 2; j++) {long y = nums[j];if (j > i + 1 && y == nums[j - 1]) {continue;}int k = j + 1;int l = n - 1;while (k<l){long s = x + y + nums[k] + nums[l];if (s > target){l--;}else if (s < target){k++;}else{ans.add(new ArrayList<>(Arrays.asList((int)x, (int)y, nums[k], nums[l])));for (k++; k < l && nums[k] == nums[k - 1]; k++) ;for (l--; k < l && nums[l] == nums[l + 1]; l--) ;}}}}return ans;}
http://www.xdnf.cn/news/7890.html

相关文章:

  • 【Linux系统】第七节—git+cgdb(详解)
  • MySQL 中 information_schema.processlist 使用原理
  • RT_Thread——内存管理
  • golang库源码学习——Pond,小而精的工作池库
  • git仓库代码操作
  • springboot+vue实现鲜花商城系统源码(带用户协同过滤个性化推荐算法)
  • 【WebRTC】源码更改麦克风权限
  • Redis 8.0 GA,重回开源
  • Wireshark抓包分析小程序接口请求教程
  • Nginx配置同一端口不同域名或同一IP不同端口
  • day32 python解释性库PDPbox
  • java 代码查重(三)常见的距离算法和相似度(相关系数)计算方法
  • 养生指南:五维升级健康生活
  • 23种经典设计模式(GoF设计模式)
  • 【苍穹外卖】Day01—Mac前端环境搭建
  • leetcode hot100刷题日记——7.最大子数组和
  • systick滴答定时器us延时和毫秒延时
  • 自动获取新版本 js 静态文件
  • 计算机网络-MPLS VPN报文转发
  • Redis面试题全面解析:从基础到底层实现
  • Python Seaborn 高级可视化指南
  • Datawhale 5月llm-universe 第4次笔记
  • 游戏引擎学习第302天:使用精灵边界进行排序
  • 化工行业质检LIMS 系统应用 原材料与成品质量追溯智能化方案
  • Hass-Panel - 开源智能家居控制面板
  • LeetCode222_完全二叉树的结点个数
  • vscode离线安装组件工具vsix
  • 《微服务架构设计模式》笔记
  • PyTorch中cdist和sum函数使用详解
  • 【图像大模型】深度解析RIFE: 基于中间流估计的实时视频插帧算法