Leetcode 18 三数之和

编程入门 行业动态 更新时间:2024-10-20 15:51:26

Leetcode 18 三数<a href=https://www.elefans.com/category/jswz/34/1768625.html style=之和"/>

Leetcode 18 三数之和

//双指针,不过因为是三个数所以左侧是两个下标class Solution {public List<List<Integer>> threeSum(int[] nums) {int n = nums.length;Arrays.sort(nums);List<List<Integer>> ans = new ArrayList<List<Integer>>();for(int i = 0; i < n; i++){if(i > 0 && nums[i] == nums[i - 1]) continue;int target = -nums[i];int k = n - 1;for(int j = i + 1; j < n; j++){if(j > i + 1 && nums[j] == nums[j - 1]) continue;while(j < k && nums[j] + nums[k] > target){k--;}if(j == k) break;if(nums[j] + nums[k] == target){List<Integer> tmp = new ArrayList<>();tmp.add(nums[i]);tmp.add(nums[j]);tmp.add(nums[k]);ans.add(tmp);}}}return ans;}
}

更多推荐

Leetcode 18 三数之和

本文发布于:2023-12-03 11:10:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1654706.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:之和   Leetcode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!