zoukankan      html  css  js  c++  java
  • 【LeetCode】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:

    • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
    • 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)
    public class Solution {
        public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
            ArrayList<ArrayList<Integer>> re = new ArrayList<ArrayList<Integer>>(); 
            Map<ArrayList<Integer>,Integer> map = new HashMap<ArrayList<Integer>,Integer>();
            ArrayList<Integer> ai = new ArrayList<Integer>();
            if(num.length<=2)
                return re;
            Arrays.sort(num);
            for(int i=0;i<num.length-2;i++){
                int temp = num[i];
                ai = new ArrayList<Integer>();
                ai.add(temp);
                int start = i+1;
                int end=num.length-1;
                int target = -temp;
                while(end>start){
                    if(num[start]+num[end]==target){
                        ai.add(num[start]);
                        ai.add(num[end]);
                        map.put(ai, 1);
                        ai=new ArrayList<Integer>();
                        ai.add(temp);
                        start++;
                        end--;
                        continue;
                    }
                    if(num[start]+num[end]>target){
                        end--;
                        continue;
                    }
                    if(num[start]+num[end]<target){
                        start++;
                        continue;
                    }
                }
            }
            re.addAll(map.keySet());
            return re;
            
        }
    }
  • 相关阅读:
    Hdu 1257最少拦截系统
    删除mysql__转
    sql 入门的小例子熟悉一下_这可是一个转转转贴 :)
    header 用法_转
    java_json 转换 文件在file中
    javascript_php 正则匹配 转
    mysql 忘记密码转_kinghu
    php 通用下载
    明天就是新年开始
    翻译 有助于程序命名
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3742648.html
Copyright © 2011-2022 走看看