leetcode-3SUM(三数相加等于0)

Given an array nums of n integers, are there elements abc in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]]

Java:

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class ThreeSum {
    public static List<List<Integer>> threeSum(int[] nums) {
        //先将数组进行升序排序
        Arrays.sort(nums);
        LinkedList result = new LinkedList();
        //先选择一个数,然后在后面的挑选两个元素求和,因此i < num.length - 2
        for(int i = 0; i < nums.length - 2; i++){
            //定义两个指针
            int lo,hi,sum;
            //当i=0时,意味着第一次遍历,当i>0时,若num[i]==num[i-1],则可以跳过该元素(因为数组是有序的)
            if(i == 0 || nums[i] != nums[i-1]){
                //低位指针从i+1开始,避免重复元祖
                lo = i+1;
                //高位指针从最后一个元素开始
                hi = nums.length-1;
                while (lo < hi){
                    sum = 0 - nums[i];
                    if(sum == nums[lo]+nums[hi]){
                        result.add(Arrays.asList(nums[i],nums[lo],nums[hi]));
                        //若当前指针元素与移动方向上的下一个指针元素相同,则跳过(此处要做++(--)操作才能跳过)
                        while (lo<hi && nums[lo] == nums[lo+1]) {
                            lo++;
                        }
                        while (lo<hi && nums[hi] == nums[hi-1]) {
                            hi--;
                        }
                        lo++;
                        hi--;
                    }
                    //若两数之和小于0,则lo++;大于0则hi--
                    else if(nums[lo]+nums[hi] < sum) lo++;
                    else hi--;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums= new int[]{-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6};
        System.out.println(Arrays.deepToString(threeSum(nums).toArray()));
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值