[Day9]15. 3Sum

This one is for my missed Day7. So there is still one problem needed for Day8.

DESCRIPTION:
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]
]

ANALYSIS:
Thank to some novel ideas learned from [16.3Sum Closest]. I finally figure out a solution, though a TLE. But some Java solutions in 'discussion' is also TLE.
Considered that ‘The solution set must not contain duplicate triplets.’, so some details are supposed to be payed attention. For example, how to choose the next DIFFERENT number--which takes me a lot of time to deal.

SOLUTION:

public static List<List<Integer>> threeSum(int[] nums) {
    List<List<Integer>> results = new ArrayList<List<Integer>>();
    Arrays.sort(nums);
    for (int i = 0; i < nums.length - 2; i++) {
        //deal different
        if (i == 0 || nums[i] != nums[i - 1]) {
            int starti = i + 1;
            int endi = nums.length - 1;
            while (starti < endi) {
                int sum = nums[i] + nums[starti] + nums[endi];
                if (sum == 0) {
                    List<Integer> result = new ArrayList<Integer>();
                    result.add(nums[i]);
                    result.add(nums[starti]);
                    result.add(nums[endi]);
                    results.add(result);

                    int lastMid = nums[starti];
                    starti++;
                    endi--;
                    //deal different
                    while (nums[starti] == lastMid && starti < endi) {
                        starti++;
                    }
                } else if (sum < 0) {
                    starti++;
                } else if (sum > 0) {
                    endi--;
                }
            }
        }
    }
    return results;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,056評(píng)論 0 23
  • maven中的scope表示的是標(biāo)簽指定的插件或者依賴,在maven項(xiàng)目生命周期的哪個(gè)部分有效。 可用的取值包括以...
    小孩真笨閱讀 297評(píng)論 0 0
  • 我最愛在半夜無人時(shí)在我精神的曠原里嘶吼 用沒人聽到的破鑼嗓 吼出所有一切情緒 我的喜怒哀樂 我的無人知道的喜怒哀樂...
    生活閱讀 416評(píng)論 0 3
  • 原來在你眼里,那些愛都是強(qiáng)迫,都是傷害,原來你心里從來沒有真正意義上的接受過我,所以才什么都不為我辯解,所以才走得...
    新生丫頭閱讀 115評(píng)論 0 0
  • 晨起略遲緩,未食,收拾行裝,將赴湛江、茂名、雲(yún)浮出差也。上午,加班甚力。中午,乘車至湛江,路上讀通鑑約一百余頁。k...
    寒窗寄傲生閱讀 94評(píng)論 0 0

友情鏈接更多精彩內(nèi)容