LeetCode OJ算法题(十七):4Sum

来源:互联网 发布:数据库的基本对象是 编辑:程序博客网 时间:2024/06/05 14:15

题目:

Given an array S of n integers, are there elements abc, 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一样,只是多一次循环而已,a[i] 和a[j]相加的条件变为target-a[k]-a[m]

import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class No17_FourSum {public static void main(String[] args){System.out.println(fourSum(new int[]{1,0,-1,0,-2,2}, 0));}public static List<List<Integer>> fourSum(int[] num, int target) {        List<List<Integer>> ret = new ArrayList<List<Integer>>();        if(num.length < 4) return ret;Arrays.sort(num);int k_pre = num[num.length-1]+1;for(int k=0;k<num.length-3;k++){if(num[k] == k_pre) continue;k_pre = num[k];int m_pre = num[num.length-1]+1;for(int m=k+1;m<num.length-2;m++){if(num[m] == m_pre) continue;m_pre = num[m];int i = m+1;int j = num.length-1;int i_pre = num[num.length-1]+1;int j_pre = num[num.length-1]+1;while(i<j){if(num[i]+num[j] < target-num[k]-num[m]){do{i++;}while(i<j && num[i] == i_pre);if(i<j)i_pre = num[i];continue;}if(num[i]+num[j] > target-num[k]-num[m]){do{j--;}while(i<j && num[j] == j_pre);if(i<j)j_pre = num[j];continue;}ArrayList<Integer> element = new ArrayList<Integer>();element.add(num[k]);element.add(num[m]);element.add(num[i]);element.add(num[j]);ret.add(element);i_pre = num[i];j_pre = num[j];do{i++;}while(i<j && num[i] == i_pre);do{j--;}while(i<j && num[j] == j_pre);if(i<j){i_pre = num[i];j_pre = num[j];}}}}        return ret;    }}


0 0
原创粉丝点击