4 sum

作者: sherrysack | 来源:发表于2018-05-28 09:42 被阅读0次

4 sum

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

Thoughts:

Using the same idea used in 3 sum, and I transferred from the 3sum version.

The idea is to make sure each number would not repeat itself in the next for loop.

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> lst = new ArrayList<>();
        Arrays.sort(nums);
        for(int j = 0; j < nums.length-2; j++) {
            if(j == 0 || (nums[j] != nums[j-1])) {
                for(int i = j+1; i< nums.length-1; i++) {
                    if(i == j+1 ||(nums[i] != nums[i-1])) {
                        int lo = i+1, hi = nums.length-1, sum = target-nums[i]-nums[j];
                        while(lo < hi) {
                            if(nums[lo]+nums[hi] == sum) {
                                lst.add(Arrays.asList(nums[j], nums[i], nums[lo], nums[hi]));
                                while(lo < hi && nums[lo] == nums[lo+1]) lo++;
                                while(hi > lo && nums[hi] == nums[hi-1]) hi--;
                                lo++; hi--;
                            }
                            else if(nums[lo]+nums[hi] < sum) {
                                lo++;
                            }else {
                                hi--;
                            }
                        }
                    }
                }
            }

        }
        return lst;
            
    }
}

相关文章

  • two sum&&three sum&&four sum&&th

    two sum 3 sum 3Sum Closest 4 sum 利用set来实现: 3 sum 4 sum

  • PowerBI DAX CALCULATE/SUM/COUNT/

    SUM CALCULATE(SUM...) COUNT 4.COUNTROWS COUNTBLANK 计算空值的个数

  • 二维数组

    sum()的函数原型:int sum( int (*ar2)[4], int size );//传递一个指向由 4...

  • 写一个sum函数使得以下表达式的值正确

    sum(1,2,3).sumOf();//6sum(2,3)(2).sumOf();//7sum(1,2,3,4)...

  • 4 sum

    4 sum Given an array nums of n integers and an integer ta...

  • 4 sum

    solution 1: sort the array, then fix two,using two pointe...

  • 4 Sum

    题目 Given an array S of n integers, are there elements a, ...

  • 4 sum

    解题报告, 这个做的比较绝望, 用了two points, recursion, memorization= =,...

  • 15+18、3Sum 4Sum

    15、3Sum Example 复杂度 思路 解法 18、4Sum Example 解法

  • Day-13求和函数

    今天学习了SUM SUMIF SUMIFS的用法 1、连续区域求和=SUM(B4:B8)这里输入SUM函数选取求...

网友评论

      本文标题:4 sum

      本文链接:https://www.haomeiwen.com/subject/qeywjftx.html