天天看點

LeetCode 15. 三數之和 3Sum

給定一個包含 n 個整數的數組 

nums

,判斷 

nums

 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重複的三元組。

注意:答案中不可以包含重複的三元組。

例如, 給定數組 nums = [-1, 0, 1, 2, -1, -4],

滿足要求的三元組集合為:
[
  [-1, 0, 1],
  [-1, -1, 2]
]
      
public class Solution {
    
    List<List<Integer>> ret = new ArrayList<List<Integer>>();  
    
    public List<List<Integer>> threeSum(int[] nums) {  
        if (nums == null || nums.length < 3){
            return ret;  
        } 
        Arrays.sort(nums);  
        int len = nums.length;  
        for (int i = 0; i < len-2; i++) {  
            if (i > 0 && nums[i] == nums[i-1]){
                continue;  
            }
            find(nums, i+1, len-1, nums[i]); //尋找兩個數與num[i]的和為0  
        }  
        return ret;  
    }  
      
    public void find(int[] num, int begin, int end, int target) {  
        int l = begin, r = end;  
        while (l < r) {  
            if (num[l] + num[r] + target == 0) {  
                List<Integer> ans = new ArrayList<Integer>();  
                ans.add(target);  
                ans.add(num[l]);  
                ans.add(num[r]);  
                ret.add(ans); //放入結果集中  
                while (l < r && num[l] == num[l+1]) l++;  
                while (l < r && num[r] == num[r-1]) r--;  
                l++;  
                r--;  
            } else if (num[l] + num[r] + target < 0) {  
                l++;  
            } else {  
                r--;  
            }  
        }  
    }  
}
           
LeetCode 15. 三數之和 3Sum