15.三数之和

暴力题解

思路

  • 确定两端值 a c,找出符合要求的中间值 b

代码

//超时
public static List<List<Integer>> threeSum(int[] nums) {
    List<List<Integer>> lists = new ArrayList<>();
    if (nums == null || nums.length < 3) return lists;
    Arrays.sort(nums);
    for (int i = 0; i < nums.length - 2; i++) {
        if (nums[i] > 0) break;
        for (int j = i + 2; j < nums.length; j++) {
            int tmp = -nums[i] - nums[j];
            for (int k = i + 1; k < j; k++) {
                if (nums[k] == tmp) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[k]);
                    list.add(nums[j]);
                    if (lists.contains(list)) {
                        continue;
                    }
                    lists.add(list);
                }
            }
        }
    }
    System.out.println(lists.toString());
    return lists;
}

双指针

思路

代码

//22ms
public static List<List<Integer>> threeSum2(int[] nums) {
    List<List<Integer>> lists = new ArrayList<>();
    if (nums == null || nums.length < 3) return lists;
    int len = nums.length;
    Arrays.sort(nums);
    for (int i = 0; i < len - 2; i++) {
        if (nums[i] > 0) break;//当前数大于0,则三个数之和必大于0  终止遍历
        if (i > 0 && nums[i] == nums[i - 1]) continue;//去重
        int l = i + 1;
        int r = len - 1;
        while (l < r) {
            int sum = nums[i] + nums[l] + nums[r];
            if (sum == 0) {
                lists.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 r--;
        }
    }
    //System.out.println(lists.toString());
    return lists;
}

参考链接

灵魂画手:画解算法

posted @ 2020-06-13 15:35  YH_Simon  阅读(155)  评论(0编辑  收藏  举报