力扣三数之和

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/3sum
 

这道题和力扣第一个题有相似之处。第一题是在数字中找一个target,看存在不存在两个数的值等于等于这个target,那道题是拿每一个数和后边的其他的数字进行组合,看有没有等于target的,满足即可,想一下,在这里,target就变了一下,如果两个数的和等于负的target,即可满足题意

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i+1; j < nums.length; j++) {
                if(nums[i]+nums[j]==target){
                    return new int[]{i,j};
                }
            }
        }
        return new int[0];
    }
}

思路是这样的,先将数组进行排序,寻找三个数的和是0,转变为对每一个数寻找有没有两个数的和等于这个数的相反数,如果满足的话,就是用list将这个三个数存起来,寻找两个数相加和时使用双指针遍历,

这里注意题目要求不使用重复值,所以要注意当数组两个相邻的数相等时,直接跳过。

另外对每一个进行查找时也要注意相同的值直接跳过。

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
                int target=0;
        Arrays.sort(nums);//先排序
        List<List<Integer>> ans = new ArrayList<>();
        int l, r;
        for (int i = 0; i < nums.length; i++) {
            if(i>0&&nums[i]==nums[i-1]) continue;
            target = 0 - nums[i];//从后边找这个数字 主要看有没有两数和是这个目标
            l = i + 1;
            r = nums.length-1;
            while (l < r) {
                if (nums[l] + nums[r] == target) {
                    List<Integer> temp = new ArrayList<>();
                    temp.add(nums[i]);
                    temp.add(nums[l]);
                    temp.add(nums[r]);
                    ans.add(temp);
                    while(l<r && nums[l]==nums[l+1]) l++;
                    while(l<r && nums[r]==nums[r-1]) r--;
                    l++;
                    r--;
                }else if(nums[l]+nums[r]<target){
                    l++;
                }else {
                    r--;
                }
            }
        }
        return ans;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值