四数之和——LinkCode

给一个包含n个数的整数数组S,在S中找到所有使得和为给定整数target的四元组(a, b, c, d)。

样例

例如,对于给定的整数数组S=[1, 0, -1, 0, -2, 2]和 target=0. 满足要求的四元组集合为:

(-1, 0, 0, 1)

(-2, -1, 1, 2)

(-2, 0, 0, 2)

注意

四元组(a, b, c, d)中,需要满足a <= b <= c <= d

答案中不可以包含重复的四元组。

public class Solution {
    /**
     * @param numbers : Give an array numbersbers of n integer
     * @param target : you need to find four elements that's sum of target
     * @return : Find all unique quadruplets in the array which gives the sum of
     *           zero.
     */
    public ArrayList<ArrayList<Integer>> fourSum(int[] numbers, int target) {
        /* your code */
       Arrays.sort(numbers);
		int len = 0;
		if(target >= 0)
		{
			for(int i=0;i<numbers.length;i++)
				if(numbers[i] >= target)
				{
					len = i;
					break;
				}
		}
		else {
			len = numbers.length-1;
		}
        ArrayList<ArrayList<Integer>> arrayList = new ArrayList<>();
		 for(int i=0;i<=len;i++)
			 for(int j=i+1;j<numbers.length;j++)
				 for(int k=j+1;k<numbers.length;k++)
					 for(int h=k+1;h<numbers.length;h++)
						{
							 if(numbers[h]+numbers[i] + numbers[j] + numbers[k] == target)
							 {
								 ArrayList<Integer> list = new ArrayList<>();
								 int[] x = {numbers[i],numbers[j],numbers[k],numbers[h]};
								 Arrays.sort(x);;
								 list.add(x[0]);
								 list.add(x[1]);
								 list.add(x[2]);
								 list.add(x[3]);
								 if(arrayList.contains(list) == false)
									 arrayList.add(list);
								 break;
							 }
						}
		 return arrayList;
    }
}


你可能感兴趣的:(面试,lintcode)