码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 15 三数之和

时间:2020-01-12 15:14:56      阅读:48      评论:0      收藏:0      [点我收藏+]

标签:pre   tco   整数   元素   数据结构   结构   怎么   集合   哈希   

  

  给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

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

 1 class Solution {
 2     public List<List<Integer>> threeSum(int[] nums) {
 3         List<List<Integer>> result=new ArrayList<List<Integer>>();
 4         Set<List<Integer>> tempSet=new HashSet<List<Integer>>();
 5         Arrays.sort(nums);
 6         int left=0;
 7         int right=0;
 8         for(int i=0;i<nums.length-2;i++){
 9             if(nums[i] > 0) break;
10             if(i > 0 && nums[i] == nums[i-1]) continue; 
11             left=i+1;
12             right=nums.length-1;
13             while(left<right){
14                 if(nums[right]+nums[left]>-nums[i]){
15                     right--;
16                 }else if(nums[right]+nums[left]<-nums[i]){
17                     left++;
18                 }else{
19                     List<Integer> temp=new ArrayList<Integer>();
20                     temp.add(nums[right]);
21                     temp.add(nums[left]);
22                     temp.add(nums[i]);
23                     tempSet.add(temp);
24                     left++;
25                 }
26             }
27         }
28         Iterator it=tempSet.iterator();
29         while(it.hasNext()){
30             result.add((List<Integer>)it.next());
31         }
32         return result;
33     }
34 }

反思:

  1,找出和为0的三个数并不难,用双指针法,难点在于怎么去除重复的答案,我用了额外的哈希集合这种数据结构。

leetcode 15 三数之和

标签:pre   tco   整数   元素   数据结构   结构   怎么   集合   哈希   

原文地址:https://www.cnblogs.com/xiaoyaomianbiren/p/12182496.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!