[LeetCode] 15. 3Sum ☆☆


 

Given an array S of n integers, are there elements abc 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]
]

 

解法:

  首先對原數組進行排序,然后開始遍歷排序后的數組,這里注意不是遍歷到最后一個停止,而是到倒數第三個就可以了,中間如果遇到跟前一個數相同的數字就直接跳過。對於遍歷到的數,如果大於0則跳到下一個數,因為三個大於0的數相加不可能等於0;否則用0減去這個數得到一個sum,我們只需要再之后找到兩個數之和等於sum即可,這樣一來問題又轉化為了求two sum,這時候我們一次掃描,找到了等於sum的兩數后,加上當前遍歷到的數字,按順序存入結果中即可,然后還要注意跳過重復數字。時間復雜度為 O(n2)。代碼如下:

public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();  // 注意不能是new List<>(); List是接口
        
        if (nums == null || nums.length < 3) {
            return res;
        }
        
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            if (nums[i] > 0) {
                break;
            }
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            
            int sum = -nums[i];
            int left = i + 1, right = nums.length - 1;
            
            while (left < right) {
                if (nums[left] + nums[right] == sum) {
                    ArrayList<Integer> triplet = new ArrayList<>();
                    triplet.add(nums[i]);
                    triplet.add(nums[left]);
                    triplet.add(nums[right]);
                    res.add(triplet);
                    
                    while (left < right && nums[left++] == nums[left]) {}
                    while (left < right && nums[right--] == nums[right]) {}
                    
                } else if (nums[left] + nums[right] < sum) {
                    while (left < right && nums[left++] == nums[left]) {}
                    
                } else {
                    while (left < right && nums[right--] == nums[right]) {}
                }
            }
        }
        return res;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM