15. 三数之和

落日映苍穹つ 2022-09-08 10:28 229阅读 0赞

https://leetcode-cn.com/problems/3sum/submissions/

难度中等3668

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组。

示例 1:

  1. 输入:nums = [-1,0,1,2,-1,-4]
  2. 输出:[[-1,-1,2],[-1,0,1]]

示例 2:

  1. 输入:nums = []
  2. 输出:[]

示例 3:

  1. 输入:nums = [0]
  2. 输出:[]

提示:

  • 0 <= nums.length <= 3000
  • -105 <= nums[i] <= 105

通过次数617,705提交次数1,858,277

  1. class Solution {
  2. public List<List<Integer>> threeSum(int[] nums) {
  3. List<List<Integer>> ans = new ArrayList<List<Integer>>();
  4. //先排序(避免重复元素)
  5. Arrays.sort(nums);
  6. /*
  7. 二重循环:
  8. 1.一层循环,确定target
  9. 2.二层循环,找到两个数 == target
  10. */
  11. for(int a=0;a<nums.length;a++)
  12. {
  13. if(a>0 && nums[a] == nums[a-1]) continue;
  14. int target = -nums[a];
  15. for(int b = a+1,c=nums.length-1;b<c;b++)
  16. {
  17. if(b>a+1 && nums[b] == nums[b-1]) continue;
  18. while(b<c && nums[b]+nums[c]>target) c--;
  19. if(b!=c && (nums[b]+nums[c])==target)
  20. {
  21. List<Integer> l = new ArrayList<Integer>();
  22. l.add(nums[a]);
  23. l.add(nums[b]);
  24. l.add(nums[c]);
  25. ans.add(l);
  26. }
  27. }
  28. }
  29. return ans;
  30. }
  31. }

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_Q1NETiBA5Yqq5Yqb5a2m5Lmg55qE5qKF5a2Q_size_18_color_FFFFFF_t_70_g_se_x_16

发表评论

表情:
评论列表 (有 0 条评论,229人围观)

还没有评论,来说两句吧...

相关阅读

    相关 15. 之和

    链接:https://leetcode-cn.com/problems/3sum 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,

    相关 15.之和

    题目描述 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元