58 - 四数之和

2017.9.25

四数之和其实可以转化为三数之和。

对于数组中的每一个数,可以转化为 求解  threeSum(num[i], target - num[i])

public class Solution {
    /*
     * @param numbers: Give an array
     * @param target: An integer
     * @return: Find all unique quadruplets in the array which gives the sum of zero
     */
	public static List<List<Integer>> fourSum(int[] numbers, int target) {
        // write your code here
		List<List<Integer>> res = new LinkedList<>();
		int length = numbers.length;
		if(length <= 3){
			return res;
		}
		Arrays.sort(numbers);
		for(int i = 0 ; i < length ; i++){
			int []num = new int[length-1-i];
			num = Arrays.copyOfRange(numbers, i+1, length);
			List<List<Integer>> list = new LinkedList<>();
			list = threeSum(num,target-numbers[i]);
			for(int k = 0; k < list.size();k++){
				List<Integer> tmp = new LinkedList<>();
				List<Integer> tmp1 = list.get(k);
				tmp.add(numbers[i]);
				tmp.addAll(tmp1);
				res.add(tmp);	
			}
			while(i < length-1 && numbers[i] == numbers[i+1]){
				i++;
			}
				
		}
		return res;
    }
	public static List<List<Integer>> threeSum(int[] numbers, int target) {
        // write your code here
		List<List<Integer>> res = new LinkedList<>();
		Arrays.sort(numbers);
		int length = numbers.length;
		if(length <=2){
			return res;
		}
		for(int i = 0 ; i < length;i++){
			// 这里是为了跳过重复的元素
			for(int j = i+1; j < length; j++){
				for(int h = j+1; h < length; h++){
					if(h != length -1 && numbers[h] == numbers[h+1]){
						continue;
					}
					if(numbers[j] + numbers[h] + numbers[i] == target){
						LinkedList<Integer> list = new LinkedList<Integer>();
						list.add(numbers[i]);
						list.add(numbers[j]);
						list.add(numbers[h]);
						if(res.contains(list)){
							continue;
						}
						res.add(list);
					}
					while(h != length -1 && numbers[h] == numbers[h+1]){
						h++;
					}
				}
				while(j != length -1 && numbers[j] == numbers[j+1]){
					j++;
				}
			}
			while(i != length-1 && numbers[i] == numbers[i+1]){
				i++;
			}
		}
		
		return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值