LeetCode记录之——fourSum

前面几道题做完的话,这个就完全不用担心,甚至连find函数都是一样的

public class Solution {
    public List<List<Integer>> fourSum(int[] num, int target){
			List<List<Integer>> res = new ArrayList<List<Integer>>();
			Arrays.sort(num);
			int len = num.length;
			for(int i = 0; i < len-3; i++){
				for(int j = i+1; j < len - 2; j++){
					List<Integer> two = find(num, j+1 ,target - num[i] - num[j]);
					for(int k = 0; k < two.size(); k+=2){
						List<Integer> tmp = new ArrayList<Integer>();
						tmp.add(num[i]);
						tmp.add(num[j]);
						tmp.add(num[two.get(k)]);
						tmp.add(num[two.get(k+1)]);
						res.add(tmp);
					}
					while(j < len -2 && num[j] == num[j+1]){
						j++;
					}
				}
				while(i < len - 3 && num[i] == num[i+1]){
					i++;
				}
			}
			return res;
		}
		public List<Integer> find(int[] num, int start, int key){
			List<Integer> result = new ArrayList<Integer>();
			int p = start;
			int q = num.length - 1;
			while(p < q){
				if(num[p] + num[q] < key){ p++; }
				else if(num[p] + num[q] > key){ q--; }
				else{
					result.add(p);
					result.add(q);
					while(p < q && num[p] == num[p+1]){
						p++;
					}
					p++;
					q--;
				}
			}
			return result;
		}
}


你可能感兴趣的:(LeetCode记录之——fourSum)