设为首页 加入收藏

TOP

[LeetCode]3Sum,解题报告
2015-11-21 02:05:14 来源: 作者: 【 】 浏览:8
Tags:LeetCode 3Sum 解题 报告

题目

Given an array S of n integers, are there elements a, b, c 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.

\

思路

开始想用深搜解决,后来发现用深搜很难保证结果没有重复的结合,因此采用排序+双指针固定解决思路,同时增加去除重复的判断机制

AC代码

public class Solution {
    public List
  
   > threeSum(int[] num) {
        List
   
    > res = new ArrayList
    
     >(); if (num.length < 3) { return res; } Arrays.sort(num); for (int i = 0; i < num.length - 2; i++) { // avoid duplicate if (i == 0 || num[i] > num[i - 1]) { int start = i + 1; int end = num.length - 1; while (start < end) { int stand = num[i] + num[start] + num[end]; if (stand == 0) { ArrayList
     
       tmp = new ArrayList
      
       (); tmp.add(num[i]); tmp.add(num[start]); tmp.add(num[end]); res.add(tmp); start++; end--; //avoid duplicate while (start < end && num[start] == num[start - 1]) { start ++; } while (start < end && num[end] == num[end + 1]) { end --; } } else if (stand > 0) { end--; } else { start++; } } } } return res; } }
      
     
    
   
  


后记

在家呆了5天就要回帝都去阿里上班了,不舍得爸妈,努力工作,争取早点财务自由!多花时间陪陪家人。
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇DM8168 GPIO驱动与测试程序 下一篇POJ 1125-Stockbroker Grapevine

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: