zoukankan      html  css  js  c++  java
  • 15.3sum

    题目链接:https://leetcode.com/problems/3sum/description/

    题目大意:与第一题类似,这个题是要求三数之和等于0,且结果不能重复。

    解法一:两层for循环,先排序,拿出一个数,对剩余的数组进行第一题类似的两数求和操作,方法可以照搬第一题,可以用两指针移动,也可以用hash表。这里用的两指针移动。还有要注意的点是要剪枝去除重复值。代码如下(耗时73ms):

     1     public List<List<Integer>> threeSum(int[] nums) {
     2         int cnt = 0;
     3         //排序
     4         Arrays.sort(nums);
     5         int low = 0, high = 0, length = nums.length;
     6         List<List<Integer>> res = new ArrayList<List<Integer>>();
     7         for(int i = 0; i < length - 2; i++) {
     8             //因为不能有重复结果,如果第一个数值相同,剪枝
     9             if(i != 0 && nums[i] == nums[i - 1]) {
    10                 continue;
    11             }
    12             for(low = i + 1, high = length - 1; low < high; ) {
    13                 cnt = nums[low] + nums[high] + nums[i];
    14                 if(cnt > 0) {
    15                     high--;
    16                 }
    17                 else if(cnt < 0) {
    18                     low++;
    19                 }
    20                 else {
    21                     List<Integer> listIn = new ArrayList<Integer>();
    22                     listIn.add(nums[i]);
    23                     listIn.add(nums[low]);
    24                     listIn.add(nums[high]);
    25                     res.add(listIn);
    26                     //剪枝,跳过重复数值
    27                     while(low < high && nums[low] == nums[low + 1]) {
    28                         low++;
    29                     }
    30                     while(low < high && nums[high] == nums[high - 1]) {
    31                         high--;
    32                     }
    33                     low++;
    34                     high--;
    35                 }
    36             }
    37         }
    38         return res;
    39     }
    View Code
  • 相关阅读:
    HTML+CSS知识点总结
    消灭textarea中的神秘空格
    OAuth2.0
    C# task和timer实现定时操作
    C# 多线程task
    EF的使用
    支付宝支付开发
    Basic Auth
    C#中匿名函数、委托delegate和Action、Func、Expression、还有Lambda的关系和区别
    [转]CodeSite使用小结
  • 原文地址:https://www.cnblogs.com/cing/p/8206676.html
Copyright © 2011-2022 走看看