4Sum, Leetcode 解题笔记

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)

跟3Sum完全一样,只是多了一层循环,懒得写了,网上找了个代码,此代码中的HashSet用法值得借鉴:

public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
	Arrays.sort(num);
 
	HashSet<ArrayList<Integer>> hashSet = new HashSet<ArrayList<Integer>>();
	ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
 
	for (int i = 0; i < num.length; i++) {
		for (int j = i + 1; j < num.length; j++) {
			int k = j + 1;
			int l = num.length - 1;
 
			while (k < l) {
				int sum = num[i] + num[j] + num[k] + num[l];
 
				if (sum > target) {
					l--;
				} else if (sum < target) {
					k++;
				} else if (sum == target) {
					ArrayList<Integer> temp = new ArrayList<Integer>();
					temp.add(num[i]);
					temp.add(num[j]);
					temp.add(num[k]);
					temp.add(num[l]);
 
					if (!hashSet.contains(temp)) {
						hashSet.add(temp);
						result.add(temp);
					}
 
					k++;
					l--;
				}
			}
		}
	}
 
	return result;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s