找出数组中三个数之和为0的组合

找出数组中三个数之和为0的组合

题目

  1. 给定一个无序可重复整数序列,当该序列中任意三个数的和等于0,输出这三个数。如:序列nums=[-1,0,1,2,-1,-4],输出[[-1,0,1],[-1,-1,2]]

思路

首先对数组不同位进行两两结合,在进行一轮循环,看刚才结合的两组相加和不同位的数之和是否等于0

代码

public class ThreeNumbersSum { 

    public static void main(String[] args) { 
        int[] nums = new int[]{ -1, 0, 1, 2, -3, -4};
        List<int[]> ts = ts(nums);
        ts.forEach(arr -> { 
            System.out.println(Arrays.toString(arr));
        });
    }

    public static List<int[]> ts(int[] nums) { 

        if (nums == null || nums.length < 3) { 
            return new ArrayList<>();
        }
        int length = nums.length;
        List<int[]> resultList = new ArrayList<>();
        if (length == 3) { 
            if (nums[0] + nums[1] + nums[2] != 0) { 
                return null;
            } else { 
                resultList.add(nums);
                return resultList;
            }
        }

        // 将数组中不同位置的数进行求和,并记录位置
        List<Temp> maps = new ArrayList<>();
        for (int i = 0; i < length - 1; i++) { 
            for (int j = i + 1; j < length; j++) { 
                Temp temp = new Temp();
                temp.index[0] = i;
                temp.index[1] = j;
                temp.sum = nums[i] + nums[j];
                maps.add(temp);
            }
        }
        // 将第三个数和刚才那两个数之和相加,看是否等于0
        for (int i = 0; i < length; i++) { 
            for (Temp temp : maps) { 
                int[] index = temp.index;
                if (index[0] >= i || index[1] >= i) { 
                    continue;
                }
                if (temp.sum + nums[i] == 0) { 
                    temp.index[2] = i;
                    resultList.add(new int[]{ nums[index[0]], nums[index[1]], nums[i]});
                }
            }
        }

        return resultList;
    }
}
class Temp { 

    int[] index = new int[3];

    int sum;
}
    原文作者:不可食用盐
    原文地址: https://blog.csdn.net/qq_43672627/article/details/114254782
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞