4sum implementation in Java from leetcode

前端 未结 6 794
生来不讨喜
生来不讨喜 2021-01-07 11:50

The problem statement from leetcode says:

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Fin

6条回答
  •  旧时难觅i
    2021-01-07 11:59

    Here is an O(n^3) solution

    import java.util.Arrays;
    import java.util.ArrayList;
    import java.util.HashSet;
    public class Solution {
    public ArrayList> fourSum(int[] num, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
    
        Arrays.sort(num);
        HashSet> hSet = new HashSet>();
        ArrayList> result = new ArrayList>();
        for (int i = 0; i < num.length; i++) {
            for (int j = i + 1; j < num.length; j++) {
                for (int k = j + 1, l = num.length - 1; k < l;) {
                    int sum = num[i] + num[j] + num[k] + num[l];
                    if (sum > target) {
                        l--;
                    }
                    else if (sum < target) {
                        k++;
                    }
                    else if (sum == target) {
                        ArrayList found = new ArrayList();
                        found.add(num[i]);
                        found.add(num[j]);
                        found.add(num[k]);
                        found.add(num[l]);
                        if (!hSet.contains(found)) {
                            hSet.add(found);
                            result.add(found);
                        }
    
                        k++;
                        l--;
    
                    }
                }
            }
        }
        return result;
    }
    

    }

提交回复
热议问题