[LeetCode] 15. 3Sum

</br>


Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

</br>

Solution

The solution to this problem is to iterate all possible nums[i], nums[j], and then check whether 0-nums[i]-nums[j] is in the array. And to check whether 0-nums[i]-nums[j] is in the array, we can use Array.binarySearch() to return the position of the target number. If the index is above 0, then it means there should be a target answer; and then we can output this array.

Additionally, we have to take care of repetition of the different expression of the actually same array. For example,

[-1,0,1], [-1,1,0], [0,-1,1]...

To solve this, we can first sort three numbers from minimum to maximum, and then store the array into a set. As a Set will get rid of the competition array, in this way, we can output only one expression of the same array.

However, when encountering large number of data, this may result in TLE. Hence, we should skip the unnecessary iteration and improve the efficiency. By adding the following code, we can skip the same number when there's more than two same numbers.

if (i > 1 && nums[i] == nums[i-2]) {              // skip same result
    continue;
}

The code is shown as below.

Java

public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        
        List ans = new ArrayList();
        Set set = new HashSet();
        
        Arrays.sort(nums);
        
        for (int i=0;i<nums.length;i++){
            
            if (i > 1 && nums[i] == nums[i-2]) {              // skip same result
            continue;
            }
            
            for (int j=i+1;j<nums.length;j++){
                int target = 0 - nums[i] - nums[j];
                int index = Arrays.binarySearch(nums, target);
                if(index >= 0 && index != i && index != j){
                    
                    int min = Math.min(nums[i],nums[j]);
                    min = Math.min(min,target);
                    int max = Math.max(nums[i],nums[j]);
                    max = Math.max(max,target);
                    
                    set.add(Arrays.asList(min, 0-min-max, max));
                }
            }
        }
        
        ans.addAll(set);
        return ans;
    }
}

</br>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末邻悬,一起剝皮案震驚了整個濱河市砌梆,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌容客,老刑警劉巖郊尝,帶你破解...
    沈念sama閱讀 218,858評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件二跋,死亡現(xiàn)場離奇詭異,居然都是意外死亡流昏,警方通過查閱死者的電腦和手機扎即,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來横缔,“玉大人铺遂,你說我怎么就攤上這事【ジ眨” “怎么了襟锐?”我有些...
    開封第一講書人閱讀 165,282評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長膛锭。 經(jīng)常有香客問我粮坞,道長,這世上最難降的妖魔是什么初狰? 我笑而不...
    開封第一講書人閱讀 58,842評論 1 295
  • 正文 為了忘掉前任莫杈,我火速辦了婚禮,結(jié)果婚禮上奢入,老公的妹妹穿的比我還像新娘筝闹。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,857評論 6 392
  • 文/花漫 我一把揭開白布关顷。 她就那樣靜靜地躺著糊秆,像睡著了一般。 火紅的嫁衣襯著肌膚如雪议双。 梳的紋絲不亂的頭發(fā)上痘番,一...
    開封第一講書人閱讀 51,679評論 1 305
  • 那天,我揣著相機與錄音平痰,去河邊找鬼汞舱。 笑死,一個胖子當(dāng)著我的面吹牛宗雇,可吹牛的內(nèi)容都是我干的昂芜。 我是一名探鬼主播,決...
    沈念sama閱讀 40,406評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼逾礁,長吁一口氣:“原來是場噩夢啊……” “哼说铃!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起嘹履,我...
    開封第一講書人閱讀 39,311評論 0 276
  • 序言:老撾萬榮一對情侶失蹤腻扇,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后砾嫉,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體幼苛,經(jīng)...
    沈念sama閱讀 45,767評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年焕刮,在試婚紗的時候發(fā)現(xiàn)自己被綠了舶沿。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,090評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡配并,死狀恐怖括荡,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情溉旋,我是刑警寧澤畸冲,帶...
    沈念sama閱讀 35,785評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站观腊,受9級特大地震影響邑闲,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜梧油,卻給世界環(huán)境...
    茶點故事閱讀 41,420評論 3 331
  • 文/蒙蒙 一苫耸、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧儡陨,春花似錦褪子、人聲如沸量淌。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,988評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽类少。三九已至叙身,卻和暖如春渔扎,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背信轿。 一陣腳步聲響...
    開封第一講書人閱讀 33,101評論 1 271
  • 我被黑心中介騙來泰國打工晃痴, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人财忽。 一個月前我還...
    沈念sama閱讀 48,298評論 3 372
  • 正文 我出身青樓倘核,卻偏偏與公主長得像,于是被迫代替她去往敵國和親即彪。 傳聞我的和親對象是個殘疾皇子紧唱,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,033評論 2 355

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