LeetCode-15.三數(shù)之和

題目

描述

給你一個(gè)包含 n 個(gè)整數(shù)的數(shù)組 nums,判斷 nums 中是否存在三個(gè)元素 a,b,c ,使得 a + b + c = 0 ?請(qǐng)你找出所有滿足條件且不重復(fù)的三元組。

注意:答案中不可以包含重復(fù)的三元組。
示例:

給定數(shù)組 nums = [-1, 0, 1, 2, -1, -4],

滿足要求的三元組集合為:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/3sum
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。

解答

思路

  1. 排序后雙指針移動(dòng)查找符合條件的第三個(gè)指針。
  2. 原始數(shù)組中數(shù)字可能重復(fù),需要跳過
  3. 要保證第二個(gè)指針在第三個(gè)指針的左側(cè),那么如果指針重合,數(shù)組又是排過序的,可以直接跳過。節(jié)省時(shí)間。

代碼

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        int n = nums.length;
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        for (int i = 0; i < n; i++) {
            // 需要和前一個(gè)數(shù)不同
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            int third = n - 1;
            int target = -nums[i];
            for (int j = i + 1; j < n; j++) {
                // 需要和前一個(gè)數(shù)不同
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                // 要保證第二個(gè)指針在第三個(gè)指針的左側(cè)
                while (j < third && nums[j] + nums[third] > target) {
                    third--;
                }
                // 如果指針重合,隨著b的增加,就不可能有符合要求的數(shù)了,直接退出
                if (j == third) {
                    break;
                }
                if (nums[j] + nums[third] == target) {
                    List<Integer> list = new ArrayList<Integer>();
                    list.add(nums[i]);
                    list.add(nums[j]);
                    list.add(nums[third]);
                    res.add(list);
                }
            }
        }
        return res;
    }
}
?著作權(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ù)。

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