1. 程式人生 > >Leetcode刷題記——18. 4Sum(4個數字和)

Leetcode刷題記——18. 4Sum(4個數字和)

一、題目敘述:

Given an array S of n integers, are there elements abc, 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: 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]
]

Subscribe to see which companies asked this question

二、解題思路:

搞不懂,我用了和15題一模一樣的演算法,就把15題3Sum的演算法加了個迴圈和防止重複的判斷,就過了。。。。。。

(1)主體思路:迴圈前個數,然後二分查詢(所以陣列要先排序)為target減去前三數和的第個數,這樣複雜度能從O(n4)減到O(n3logn)。

完全照搬15題。。。

三、原始碼:

import java.util.ArrayList;  
import java.util.Arrays;  
import java.util.List;  
  
public class Solution   
{  
    List<List<Integer>> ans = new ArrayList<List<Integer>>();  
    public List<List<Integer>> fourSum(int[] nums, int target)   
    {  
        Arrays.sort(nums);  
        int q;  
        int h;  
        //int count = 0;  
        //List<List<Integer>> reslist = new ArrayList<List<Integer>>();  
        for (int i = 0; i < nums.length; i ++)  
        {  
            if (i > 0 && nums[i] == nums[i-1]) continue;//去除重複  
            for (int j = i + 1; j < nums.length; j++)  
            {  
                if (j > i+1 && nums[j] == nums[j-1]) continue;//去除重複  
                for (int k = j + 1; k < nums.length; k++)
                {
                	if (k > j+1 && nums[k] == nums[k-1]) continue;
                	 q = BinarySearch(target-nums[i]-nums[j]-nums[k], nums, k+1, nums.length - 1);  
                     if (q > k)  
                     {  
                         //count ++;  
                         List<Integer> list = new ArrayList<Integer>();  
                         list.add(nums[i]);  
                         list.add(nums[j]);  
                         list.add(nums[k]);
                         list.add(nums[q]);  
                         ans.add(list);  
                     }  
                }
               
            }  
        }  
          
        return ans;  
    }  
    public int BinarySearch (int k,int[] num,int first, int last)  
    {  
        //int first = 0;  
        //int last = num.length - 1;  
        int mid;  
        while (first <= last)  
        {  
            mid = (first + last) / 2;  
            if (num[mid] > k) last =mid - 1;  
            else if (num[mid] < k) first = mid + 1;  
            else return mid;  
        }  
        return -1;  
    }  
    public static void main(String args[])  
    {  
        int[] a = {1, 0, -1, 0, -2, 2};  
        Solution so = new Solution();  
        System.out.println(so.fourSum(a, 0));  
          
          
          
    }  
}