1. 程式人生 > >[LeetCode] 4Sum

[LeetCode] 4Sum

Question : 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)
思路:

Note : 這個跟3sum也挺像。     定義一對指標,指向兩頭。再定義一對指標,指向中間的兩個元素。加起來看看跟target比較一下。決定內部指標怎麼移動。

用到了Arrays.sort() 方法,該方法是一種改進的快排,時間複雜度最優情況 O(N*logN)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;

public class FourSum {

	public ArrayList fourSum (int[] num, int target) {
			HashSet rs = new HashSet();
			int len = num.length;
			Arrays.sort(num);
			if(len <= 3) return new ArrayList(rs);
			
			for(int i = 0; i < len-3; i++) {
			 for(int k = len-1; k > i+2; k--) {
			     int ab = num[i] + num[k];
			     int c = target-ab;
			     int m = i+1;
			     int n = k-1;
			     while(m < n) {
			         int sum = num[m] + num[n];
			         if(sum == c) {
			             ArrayList elem = new ArrayList();
			             elem.add(num[i]);
			             elem.add(num[m]);
			             elem.add(num[n]);
			             elem.add(num[k]);
			             rs.add(elem);
			             m++;
			             n--;
			         }
			         else if(sum < c) {
			             m++;
			         }
			         else n--;
			     }
			 }
			}
			
			return new ArrayList(rs);

		}
}