• 【leetcode】_3Sum


    • 外加一层循环,遍历数组所有数,作为第一个数,其他两个与2sum类似,a+b=target结束循环,如果小就a+,如果大就b-
    • 将满足条件的结果(三个数字)放入midresult中,midresult是个链表,将midresult放入hashmap中去重
    • 再将hashmap中取出来放入result中即可

       

    public class _3Sum {

    public static ArrayList threeSum(int[] num) {

    Arrays.sort(num);

    ArrayList result = new ArrayList();

    Map hm = new HashMap();

       

    for (int firstPos = 0; firstPos < num.length; firstPos++) {

    int secPos = firstPos + 1;

    int thirdPos = num.length - 1;

    while (secPos < thirdPos) {

    if (num[firstPos] + num[secPos] + num[thirdPos] == 0) {

    ArrayList<Integer> midResult = new ArrayList<Integer>();

    midResult.add(num[firstPos]);

    midResult.add(num[secPos]);

    midResult.add(num[thirdPos]);

    hm.put(midResult, false);

    secPos += 1;

    thirdPos -= 1;

    } else if (num[firstPos] + num[secPos] + num[thirdPos] < 0) {

    secPos += 1;

    } else {

    thirdPos -= 1;

    }

    }

    }

    Iterator it = hm.entrySet().iterator();

    while (it.hasNext()) {

    //                        Entry entry =(Entry) it.next();

    //                        result.add(entry.getKey());

    result.add(it.next());

    }

    return result;

       

    }

       

    public static void main(String[] args) {

    //                int[] num = { -1, 0, 1, 2, -1, -4,-1,0,1};

    int[] num = {0,0,0};

    System.out.println(threeSum(num));

    }

    }

  • 相关阅读:
    input填入字符会出现黄色
    安装Scrapy时出现问题scrapy unicodedecodeerror ascii codec cant decode byte 0xd1 in position
    SVN 出现:Previous operation has not finished; run 'cleanup' if it was interrupted。
    Myeclipse小技巧
    好的开发网站
    BZOJ 1968
    BZOJ 1010
    BZOJ 1015
    BZOJ 3875
    BZOJ 2705
  • 原文地址:https://www.cnblogs.com/keedor/p/4366739.html
Copyright © 2020-2023  润新知