4Sum(****) 基于3Sum

题目: 在array中找到所有的组合 a + b + c + d = target , 组合不重复且a < b < c < d

  1. 数组排序
  2. 对每一个数组中的元素arr[i] , 求3Sum target = target - arr[i] 时间复杂度 < O(n^3)
  3. 3Sum暴力的话,时间复杂度为O(n^3) , 但是对于排序的数组,对于 下标 i , j 如果 i < j arr[i] + arr[j] < target , 那么j 之后的元素就不要比较了; 所以,可以设置头尾指针,求3Sum, 如果头+尾 < target , 头+1 ,相反 尾-1 这样时间复杂度为O(n^2)
public static List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<> ();
        Arrays.sort(nums);
        for(int i = 0 ; i < nums.length;) {
            thirdSum(nums , i , target , res);
            int t = i;
            i++;
            for(;i < nums.length && nums[i] == nums[t] ; i++ );
        }
        return res;
    }

    private static void thirdSum(int[] nums, int start,
            int target, List<List<Integer>> res) {
        int len = nums.length;
        if(start + 3 >= len) return ;
        for(int i = start + 1 ; i <= len - 3; ) {
            int head = i + 1;
            int tail = len - 1;
            int tgt = target - nums[i] - nums[start];
            while(head < tail) {
                int sum = nums[head] + nums[tail];
                if(sum < tgt) {
                    head++;
                } else if (sum > tgt) {
                    tail--;
                } else {
                    List<Integer> list = new ArrayList<> ();
                    list.add(nums[start]);
                    list.add(nums[i]);
                    list.add(nums[head]);
                    list.add(nums[tail]);
                    res.add(list);
                    int tmp = head;
                    head++;
                    for(; head < len && nums[head] == nums[tmp] ; head++);
                    tmp = tail;
                    tail--;
                    for(; tail >= start && nums[tail] == nums[tmp] ; tail--);
                }
            }
            int t = i;
            i++;
            for(;i < nums.length && nums[i] == nums[t] ; i++ );
        }
    } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值