LeetCode 4Sum 解題報(bào)告

其思路類似于3sum。下面是題目和代碼。

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.
For example, given array S = {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)

import java.util.*;

public class Solution {
  public List> fourSum(int[] nums, int target) {
    List> result = new ArrayList<>();
    if (nums == null || nums.length < 4) return result;
    Arrays.sort(nums);
    int len = nums.length;
    for (int i = 0; i < len - 3; i++) {
      if (i > 0 && nums[i] == nums[i - 1]) continue; // Skip same results
      for (int j = i + 1; j < len - 2; j++) {
        if (j > 1 && i != j - 1 && nums[j] == nums[j - 1]) continue;
        int target2 = target - nums[i] - nums[j];
        int k = j + 1, l = len - 1;
        while (k < l) {
          if (nums[k] + nums[l] == target2) {
            result.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));
            while (k < l && nums[k] == nums[k + 1]) k++; // Skip same results
            while (k < l && nums[l] == nums[l - 1]) l--; // Skip same results
            k++;
            l--;
          } else if (nums[k] + nums[l] < target2) {
            k++;
          } else {
            l--;
          }
        }
      }
    }
    return result;
  }

  public static void main(String[] args) {
    int[] nums = new int[] {2,1,0,-1};
    int target = 2;
    List> result;
    Solution solution = new Solution();
    result = solution.fourSum(nums, target);
    for (List l: result) {
      for (int i = 0; i < l.size(); i++) {
        System.out.print(l.get(i));
        if (i != l.size() - 1) {
          System.out.print("+");
        }
      }
      System.out.println("="+ target);
    }
  }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容