4sum implementation in Java from leetcode

前端 未结 6 789
生来不讨喜
生来不讨喜 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条回答
  •  [愿得一人]
    2021-01-07 12:23

    Here's a solution that does not use hash. It should be faster, but it still exceeds the time limit.

    import java.util.ArrayList;
    
    public class Solution {
        public static void main(String[] args) {
    
          int[] S = {1, 0, -1, 0, -2, 2};
          int target = 0;
          test(S, target);
        }
    
        public static void test(int[] num, int target) {
          System.out.print("a:");
          for (int i : num) {
            System.out.print(" " + i);
          }
          System.out.println(": " + target);
          ArrayList> res = fourSum(num, target);
          for (ArrayList list : res) {
            System.out.println(list);
          }
          System.out.println();
        }
    
        // a+b+c+d = target
        public static ArrayList> fourSum(int[] num, int target) {
            // Start typing your Java solution below
            // DO NOT write main() function
    
           // Sort
           {
            for (int i = 0; i < num.length; i++) {
                for (int j = i + 1; j < num.length; j++) {
                    if (num[j] < num[i]) {
                        int tmp = num[i];
                        num[i] = num[j];
                        num[j] = tmp;
                    }
                }
            }
           }
          ArrayList> res = new ArrayList>();
          int i = 0;
          while (i < num.length - 3) {
            int j = i + 1;
            while (j < num.length - 2) {
                int k = j + 1, l = num.length - 1;
                while (k < l) {
                    int sum = num[i] + num[j] + num[k] + num[l];
                    if (sum > target) {
                        l--;
                        while (k < l && num[l] == num[l+1]) l--;
                    } else if (sum < target) {
                        k++;
                        while (k < l && num[k] == num[k-1]) k++;
                    } else {
                        ArrayList list =
                            new ArrayList(4);
                        list.add(num[i]); list.add(num[j]);
                        list.add(num[k]); list.add(num[l]);
                        res.add(list);
                        k++;
                        while (k < l && num[k] == num[k-1]) k++;
                        l--;
                        while (k < l && num[l] == num[l+1]) l--;
                    }
                }
                j++;
                while (j < num.length && num[j] == num[j-1]) j++;
            }
            i++;
            while (i < num.length && num[i] == num[i-1]) {
                i++;
            }
          }
    
          return res;
        }
    }
    

提交回复
热议问题