LintCode 四數(shù)之和

題目

給一個包含n個數(shù)的整數(shù)數(shù)組S,在S中找到所有使得和為給定整數(shù)target的四元組(a, b, c, d)。

注意事項

四元組(a, b, c, d)中,需要滿足a <= b <= c <= d

答案中不可以包含重復(fù)的四元組。

樣例
例如,對于給定的整數(shù)數(shù)組S=[1, 0, -1, 0, -2, 2] 和 target=0. 滿足要求的四元組集合為:

(-1, 0, 0, 1)

(-2, -1, 1, 2)

(-2, 0, 0, 2)

分析

跟三數(shù)之和思路一樣,多一層循環(huán)而已

代碼

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[] num, int target) {
        if(num == null || num.length <4)
            return new ArrayList<>();
            
            
        ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>();
        Arrays.sort(num);
        
        for(int i=0;i<num.length-3;i++) {
            if(i!=0 && num[i] ==num[i-1])
                continue;
            
            for(int j=i+1;j<num.length-2;j++) {
                if(j!=i+1 && num[j] ==num[j-1])
                    continue;
                
                int left = j+1;
                int right = num.length-1;
                
                while(left < right) {
                    int sum = num[i] + num[j] + num[left] + num[right];
                    if(sum == target) {
                        ArrayList<Integer> temp = new ArrayList<>();
                        temp.add(num[i]);
                        temp.add(num[j]);
                        temp.add(num[left]);
                        temp.add(num[right]);
                        rst.add(temp);
                        left++;
                        right--;
                        while(left<right && num[left] == num[left-1])
                            left++;
                        while(left<right && num[right] == num[right+1])
                            right--;
                    } else if(sum < target)
                        left++;
                    else
                        right--;
                    
                }
            }
        }
        return rst;
                
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容