• 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]
    ]


    此题和那几个two sum类型不同之处在于,三个数的和为0.可以用一个for循环来充当-target,在for循环里面完全当作two sum来做就可以了。关于在for循环里面应该选择什么数据结构,我一开始用了hashmap,在前面的two sum题中,hashmap的value值可以保存索引,又可以保存同样的数组值出现的次数
    看了下此题似乎不用存储索引值,如果保存key值出现的次数,感觉是可行的,但是很麻烦。后来考虑用hashset做,发现做出来后有一些测试用例过不去例如上面的例子,[-1,0,1]和[0,1,-1]他们是一样的,然而output上面是两个结果。然后我就想排序,排除掉前后数组元素
    相同的情况。但是后来有个测试用例过不去[0,0,0,0].最后决定用两个指针来做了,需要注意的是数组值前后相同的情况,遇到相同情况时候,要移动指针。代码如下:

    public class Solution {

        public List<List<Integer>> threeSum(int[] nums) {

            List<List<Integer>> res = new ArrayList<List<Integer>>();

            Arrays.sort(nums);

            for(int i=0;i<nums.length-2;i++){

                if(i!=0&&nums[i]==nums[i-1]) continue;

                int low = i+1,high = nums.length-1;

                int sum = -nums[i];

                while(low<high){

                    if(nums[low]+nums[high]==sum){

                        res.add(Arrays.asList(nums[i],nums[low],nums[high]));

                        while(low<high&&nums[low]==nums[low+1]) low++;

                        while(low<high&&nums[high]==nums[high-1]) high--;

                        low++;

                        high--;

                    }else if(nums[low]+nums[high]<sum) low++;

                    else high--;

                    

                }

            }

            return res;

        }

    }




  • 相关阅读:
    构建高性能可扩展asp.net网站--20130628
    全文索引构建的语句
    一些常用的数据性能查看命令
    【Mongodb教程 第一课 】 MongoDB下载安装
    【Mongodb教程 第一课 补加课】 Failed to connect to 127.0.0.1:27017, reason: errno:10061 由于目标计算机积极拒绝,无法连接
    一个关于MYSQL IFNULL的用法
    如何查看网站的在全国各地的打开速度
    JS 省市区三级联动
    JS地区四级级联
    简单JS全选、反选代码
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6353818.html
Copyright © 2020-2023  润新知