15. 3Sum

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

Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},

A solution set is:
(-1, 0, 1)
(-1, -1, 2)

从给出的数组中找出三个数,使其和为0,找出所有的解决方案,解决方案不能出现重复,并且每个解决方案中的三个数要升序排列。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {

    List<List<Integer>> solutionList = new ArrayList<>();
    public List<List<Integer>> threeSum(int[] nums) {
        // 将数组升序排序
        Arrays.sort(nums);

        if (nums == null)
            return solutionList;

        int len = nums.length;
        if (len < 3) {
            return solutionList;
        }

        for (int i = 0; i <= len-3; i++) {  
            if (i > 0 && nums[i] == nums[i-1]){
                continue;
            }
            //寻找两个数与num[i]的和为0  
            find(nums, i+1, len-1, nums[i]); 
        }  

        return solutionList;
    }

    /**
     * 以第0个数为目标,从第1个数和从第len-1个数逐渐往中间靠拢寻找和为0的情况,和大于0的话右边往左移动,和小于0的话左边往右移动
     * 排重:遇到和为0的情况,判断l所指的数和l+1所指的数是否相等,相等的话往右移,判断r所指的数和r-1所指的数是否相等,相等的话往左移。
     * @param num
     * @param begin
     * @param end
     * @param target
     */
    public void find(int[] num, int begin, int end, int target) {  
        int l = begin, r = end;  
        while (l < r) {  
            if (num[l] + num[r] + target == 0) {  
                ArrayList<Integer> ans = new ArrayList<Integer>();  
                ans.add(target);  
                ans.add(num[l]);  
                ans.add(num[r]);  
                //放入结果集中  
                solutionList.add(ans); 

                // 避免放入结果集的数出现重复
                while (l < r && num[l] == num[l+1]) l++;  
                while (l < r && num[r] == num[r-1]) r--;  

                // 继续寻找
                l++;  
                r--;  
            } else if (num[l] + num[r] + target < 0) {  
                l++;  
            } else {  
                r--;  
            }  
        }  
    } 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值