Leetcode第15题:三数值和

参考的文章,转载请注明出处:https://www.cnblogs.com/ganganloveu/p/3832180.html

代码以及注释如下所示:

import java.util.*;
/**
 * 先升序排序,然后用第一重for循环确定第一个数字。

 然后在第二重循环里,第二、第三个数字分别从两端往中间扫。

 如果三个数的sum等于0,得到一组解。

 如果三个数的sum小于0,说明需要增大,所以第二个数往右移。

 如果三个数的sum大于0,说明需要减小,所以第三个数往左移

 1、排序之后天然满足non-descending order的要求

 2、为了避免重复,在没有空间要求情况下可以用map,但是也可以跳过重复元素来做。
 */

public class ThreeSum_15 {

    public static void main(String[] args) {
        int []nums = new int[]{-1, 0, 1, 2, -1, -4};
        List<List<Integer>> list = new ThreeSum_15().threeSum(nums);
        for (List<Integer> pl : list){
            for(Integer i : pl){
                System.out.print(i+" ");
            }
            System.out.println();
        }
    }
    List<List<Integer>> list = new ArrayList<List<Integer>>();
    
    public List<List<Integer>> threeSum(int[] nums) {
        
        if (nums == null || nums.length == 0){
            return list;
        }
        //将数组进行排序
        Arrays.sort(nums);
        int len = nums.length;
        int i = 0, j = 0, k = 0;
        for (; i < len; i++){
            //此时已经确定了第一个数字:nums[i]
            //跳过相同的i
            while (i > 0 && i < len && nums[i] == nums[i-1]){
                i++;
            }
            for (j = i+1, k = len-1; j < k; ){
                //求三个数字的和
                int sum = nums[i] + nums[j] + nums[k];
                if (sum < 0){
                    //小于0的话,sum需要变大,第二个数往右移动
                    j++;
                }else if (sum > 0){
                    //大于0的话,sum需要减小,第三个数往左移动
                    k--;
                }else {
                    //等于0,就将三个数加入一个list集合,并将集合加入到结果集中
                    addList(nums[i], nums[j], nums[k]);
                    j++;
                    k--;
                    //当等于0之后,需要去重
                    while (j < k && nums[j] == nums[j-1]){
                        j++;
                    }
                    while (k > j && nums[k] == nums[k+1]){
                        k--;
                    }
                }
            }
        }
        return list;
    }
    
    private void addList(int first, int second, int third){
        List<Integer> sublist = new ArrayList<Integer>();
        sublist.add(first);
        sublist.add(second);
        sublist.add(third);
        list.add(new ArrayList<>(sublist));
    }


}


猜你喜欢

转载自blog.csdn.net/lmt_1234567890/article/details/80006419