leetcode刷题20

今天刷的题是LeetCode第15题,三个数之和

即给定数组的情况下,找到三个数之和为0

首先是暴力法,三层for循环,具体地代码如下:

public static List<List<Integer>> solution(int[] nums){
        //暴力法
        //超出时间限制
        int n=nums.length;
        List<List<Integer>> result=new ArrayList<>();
        for (int i = 0; i <n-2 ; i++) {
            int sum=nums[i];
            for (int j = i+1; j <n-1 ; j++) {
                int left=nums[j];
                for (int k = j+1; k <n ; k++) {
                    int right=nums[k];
                    if (left+right+sum==0){
                        List<Integer> subresult=new ArrayList<>();
                        subresult.add(sum);
                        subresult.add(left);
                        subresult.add(right);
                        Collections.sort(subresult);
                        if (!result.contains(subresult)){
                            result.add(subresult);
                        }
                    }
                }
            }
        }
        return result;
    }

但是暴力法是直接超出时间了。因此可以考虑对数组做一定的预处理。三个数之和等于0,那么对应着必须要有小于等于0的数,因此可以先对数组进行排序,然后再用双指针,代码如下:

public static List<List<Integer>> solution2(int[] nums){
        int n=nums.length;
        List<List<Integer>> result=new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < n ; i++) {
            if(nums[i] > 0) break; // 如果当前数字大于0,则三数之和一定大于0,所以结束循环
            if(i > 0 && nums[i] == nums[i-1]) continue; // 去重
            int L = i+1;
            int R = n-1;
            while(L < R){
                int sum = nums[i] + nums[L] + nums[R];
                if(sum == 0){
                    result.add(Arrays.asList(nums[i],nums[L],nums[R]));
                    while (L<R && nums[L] == nums[L+1]) L++; // 去重
                    while (L<R && nums[R] == nums[R-1]) R--; // 去重
                    L++;
                    R--;
                }
                else if (sum < 0) L++;
                else if (sum > 0) R--;
            }
        }
        return result;
    }
原文地址:https://www.cnblogs.com/cquer-xjtuer-lys/p/11448753.html