【題目描述】
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target?Find all unique quadruplets in the array which gives the sum of target.
Notice: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.
給一個(gè)包含n個(gè)數(shù)的整數(shù)數(shù)組S,在S中找到所有使得和為給定整數(shù)target的四元組(a, b, c, d)。
注意:四元組(a, b, c, d)中,需要滿足a <= b <= c <= d。答案中不可以包含重復(fù)的四元組。
【題目鏈接】
www.lintcode.com/en/problem/4sum/
【題目解析】
我們采用2sum,以及3sum的方法,先排序后,用兩趟循環(huán)循環(huán)分別遍歷第一個(gè)數(shù)和第二個(gè)數(shù),然后剩余的兩個(gè)數(shù),用二分查找的方法去找。
1.對(duì)數(shù)組排序
2.確定四元數(shù)中的前兩個(gè)(a,b)
3.遍歷剩余數(shù)組確定兩外兩個(gè)(c,d),確定cd時(shí)思路跟3Sum確定后兩個(gè)數(shù)據(jù)一樣,二分查找左右逼近。
【參考答案】