LeetCode 15. 3Sum

Description

Given an array numsof n integers, are there elements a, b, c in numssuch that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Example

在这里插入图片描述

Code

  • java
import java.util.ArrayList;
class Solution {
    public int binarySearch(int[] arr, int left, int right, int x) {
        while(left < right) {
            int mid = (left+right)/2;
            if(arr[mid] == x) {
                return mid;
            } else if(arr[mid] > x) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }
    
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Set<List<Integer>> set = new TreeSet<>();
        int len = nums.length;
        Arrays.sort(nums);
        for(int st = 0; st < len-1; st++) {
            for(int ed = len-1; ed > st; ed--) {
                if(ed != len-1 && nums[ed] == nums[ed+1]) continue;
                int diff = -(nums[st] + nums[ed]);
                int mid = binarySearch(nums, st+1, ed-1, diff);
                if(mid != st && mid != ed && nums[mid] == diff) {
                    ArrayList<Integer> temp = new ArrayList<Integer>();
                    temp.add(nums[st]);
                    temp.add(nums[mid]);
                    temp.add(nums[ed]);
                    if(!result.contains(temp)) {
                        result.add(temp);
                    }
                } 
            }
        }
        return result;
    }
}
  • Others’ solution
  • Time complexity O(N^2)
 import java.util.LinkedList;
class Solution {
    public List<List<Integer>> threeSum(int[] num) {
        Arrays.sort(num);
        List<List<Integer>> res = new LinkedList<>(); 
        for (int i = 0; i < num.length-2; i++) {
            if (i == 0 || (i > 0 && num[i] != num[i-1])) {
                int lo = i+1, hi = num.length-1, sum = 0 - num[i];
                while (lo < hi) {
                    if (num[lo] + num[hi] == sum) {
                        res.add(Arrays.asList(num[i], num[lo], num[hi]));
                        while (lo < hi && num[lo] == num[lo+1]) lo++;
                        while (lo < hi && num[hi] == num[hi-1]) hi--;
                        lo++; hi--;
                    } else if (num[lo] + num[hi] < sum) lo++;
                    else hi--;
               }
            }
        }
        return res;
    }
}

Conclusion

  • 自己想复杂了,用一个循环遍历数组后,就转化为2Sum问题,然后就可以用two-pointer思想,菜是原罪(所以一定要先想清楚再code!)
  • 数组中的其他元素可以多次利用
  • 去重
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值