zoukankan      html  css  js  c++  java
  • 力扣(LeetCode)15. 三数之和

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

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

    例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

    满足要求的三元组集合为:
    [
    [-1, 0, 1],
    [-1, -1, 2]
    ]

    思路 用HashSet无重复的特点去重。

    先将数组排序。 Arrays.sort(nums); //从小到大
    用三个指针,i指向第一个元素,j指向第二个元素,k指向第三个元素。

    java版

    class Solution {
    	public List<List<Integer>> threeSum(int[] nums) {
    		Arrays.sort(nums);
            List<List<Integer>> list = new ArrayList<List<Integer>>();
            HashSet<List<Integer>> hashset = new HashSet<>();
     
            int i,j,k,len = nums.length;
            for(i=0;i<len-2;i++) {
            	j = i+1;
            	k = len-1;
            	while(j < k) {
            		int sum = nums[i]+nums[j]+nums[k];
                	if(sum < 0) {
                		j++;
                	}else if(sum > 0) {
                		k--;
                	}else {
                		List<Integer> list1 = new ArrayList<>();
    					list1.add(nums[i]);
    					list1.add(nums[j]);
    					list1.add(nums[k]);
    					hashset.add(list1);
                       
                        j++;
                        k--;
                	}
            	}
            }
            if(hashset.size()!=0) {
            	Iterator<List<Integer>> iterator = hashset.iterator();
            	while(iterator.hasNext()) {
            		list.add(iterator.next());
            	}
            }
    		return list;
        }
    }
    

    运行结果

  • 相关阅读:
    gbk与utf-8转换
    gdb注意事项
    Ubuntu导入证书
    Ubuntu 修改hosts
    GDB配置与.gdbinit的编写
    linux中用户的主目录~
    关于C++构造函数初始化顺序
    C++中的static关键字的总结
    Flutter移动电商实战 --(2)建立项目和编写入口文件
    Flutter移动电商实战 --(1)项目学习记录
  • 原文地址:https://www.cnblogs.com/lick468/p/10658788.html
Copyright © 2011-2022 走看看