4sum implementation in Java from leetcode

前端 未结 6 756
生来不讨喜
生来不讨喜 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 11:57

    Your solution may have exceeded the time limit and therefore may have not been able to pass the test cases. Below is the code having the runtime O(n^3). Initially, we sort the array which will help us to find the element either by moving forward or backward depending on the number we are looking for. We then take the first element from the array and perform a three sum on the remaining part leading to find the two sum. Only the ArrayList is used. HashMap is not required.

    public static List> fourSum(int[] nums, int target) {
        List> result = new ArrayList>();
    
        if(nums==null|| nums.length<4)
            return result;
    
        Arrays.sort(nums);
    
        for(int i=0; itarget)
                   {
                      l--;
                   }
                   else
                   {
                      List t = new ArrayList();
                      t.add(nums[i]);
                      t.add(nums[j]);
                      t.add(nums[k]);
                      t.add(nums[l]);
                      result.add(t);
    
                      k++;
                      l--;
    
                      while( k

提交回复
热议问题