第15题 三个数的和为确定值

寻找三数之和为零
本文介绍了一种算法,用于在给定整数数组中查找所有唯一三元组,这些三元组加起来等于零。该算法首先对数组进行排序,然后使用双指针技巧遍历数组来查找符合条件的三元组。

给出一组数:V = {-8,-4,-1,-1,0,0,0,0,0,1,2,5,7}

找出所有和为0的三个元素的组合:[[-8, 1, 7], [-4, -1, 5], [-1, -1, 2], [-1, 0, 1], [0, 0, 0]]

 

基本思路:

先排序:{-8,-4,-1,-1,0,0,0,0,0,1,2,5,7}

遍历:从最左边的第一个元素i=0开始,找到i=1~j=12之间两个数的和满足0-V[i]=V[m]+V[n],m从i+1开始,n从j=12开始。若0-V[i]<V[m]+V[n],则m++。若0-V[i]>V[m]+V[n],则j--

 

注意:组合不能重复,故找到0-V[i]=V[m]+V[n]时,需要跳过V[m]右侧与V[m]相等的数,同理也要跳过所有V[n]左侧与V[n]相等的数。

 

package T015;

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

public class ThreeSum {
    static List<List<Integer>> res =new ArrayList<List<Integer>>();
    public static void main(String[] args) {
        
        System.out.println(threeSum(new int[]{-8,-4,-1,-1,0,0,0,0,0,1,2,5,7}));
    }

    public static List<List<Integer>> threeSum(int[] nums) {
           Arrays.sort(nums);  
           for(int i=0;i<nums.length-2;i++){
               if(i>0&&nums[i]==nums[i-1])   continue;   // to exclude the duplicated number
               twoSum(0-nums[i],nums,i+1,nums.length-1);
           }
           return res;
        }
    private static void twoSum(int target,int[] nums, int start,int end){ 
           int i=start,j=end;
           while(i<j){
               List<Integer> subres=new ArrayList<Integer>();
               int sum=nums[i]+nums[j];
               if(sum==target){
                    subres.add(0-target);
                    subres.add(nums[i]);
                    subres.add(nums[j]);
                    res.add(subres);
                   do {
                        i++;
                    }while(i < end && nums[i] == nums[i-1]);   // to exclude the duplicated number
                    do {
                        j--;
                    } while(j >= 0 && nums[j] == nums[j+1]); // to exclude the duplicated number
                }
                else if(sum<target) i++;
                else j--;
            }
        }
        
    public static void printList(List<Integer> list){
        System.out.print("list: ");
        for(int i=0;i<list.size();i++){
            System.out.print(list.get(i)+" ");
        }
        System.out.println("");
    }
}

 

转载于:https://www.cnblogs.com/wuchaodzxx/p/5853061.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值