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

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

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

0 <= nums.length <= 3000

−105 <= nums[i] <= 105

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/3sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

函数接口定义:

public static List<List<Integer>> threeSum(int[] nums) 

裁判测试程序样例: 

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] array = new int[n];
        for(int i = 0; i <n; i++)
            array[i] = sc.nextInt();
        List<List<Integer>> result = threeSum(array);
        for(int i = 0; i < result.size(); i++){
            List<Integer> list = result.get(i);
            for(int j = 0; j < list.size(); j++)
                System.out.print(list.get(j) + " ");
            System.out.println();
        }
    }
/* 请在这里填写答案 */

输入样例1:

第一行输入数组长度n,第二行输入数组元素,以空格间隔

6
-1 0 1 2 -1 4

输出样例1:

每个三元组一行

-1 -1 2 
-1 0 1 

输入样例2:

第一行输入数组长度n,第二行输入数组元素,以空格间隔

0

输出样例2:

每个三元组一行


输入样例3:

第一行输入数组长度n,第二行输入数组元素,以空格间隔

1
0

输出样例3:

每个三元组一行

代码如下: 

public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> lists = new ArrayList<>();
        Arrays.sort(nums);
        int length = nums.length;;
        for (int i = 0; i < length - 2; i ++) {
            int start = i + 1;
            int end = length - 1;
            while (start < end) {
                int sum = nums[i] + nums[start] + nums[end];
                if (sum == 0) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[start]);
                    list.add(nums[end]);
                    lists.add(list);
                    while (start < end && nums[start] == nums[start + 1]) {
                        start ++;
                    }
                    while (start < end && nums[end] == nums[end - 1]) {
                        end --;
                    }
                    while (start < end && nums[i] == nums[i + 1]) {
                        i ++;
                    }
                    start ++;
                    end --;
                } else if (sum < 0) {
                    start ++;
                } else if (sum > 0) {
                    end --;
                }
            }
        }
        return lists;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天的命名词

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值