zoukankan      html  css  js  c++  java
  • 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)

    【分析】

    1.使用两头逼近的方法,利用两层循环。第一层循环遍历每一个元素,在第二层循环里两头逼近找出满足条件的结果

    2.要考虑数据元素重复的问题,若第二层循环中遇到相同元素,需要继续向前;

    3.第一层循环中晕倒相同元素,也需要继续向前

    public class Solution {
        public List<List<Integer>> threeSum(int[] num) {
            List<List<Integer>> res=new ArrayList<List<Integer>>();
            Arrays.sort(res);
            for(int i=0;i<num.length;i++) {
                int start=i+1;
                int end=num.length-1;
                int target=0-num[i];
                while(start<end) {
                   if(target==num[start]+num[end]) {
                       Lsit<Integer> temp=new ArrayList<Integer>();
                       temp.add(num[i]);
                       temp.add(num[start]);
                       temp.add(num[end]); 
                       res.add(temp);
                       start++;
                       end--;
                       while(start<end&&num[start]==num[start-1])
                           start++;
                       while(start<end&&num[end]==num[end+1])
                           end--;       
                   }else if(num[start]+num[end]>target)
                       end--;
                   else 
                       start++;
                }
                while(i<num.length-1&&num[i]==num[i++])
                   i++;
            }
            return res;
        }
    }        

    【算法实现】 

     

  • 相关阅读:
    【[Offer收割]编程练习赛12 B】一面砖墙
    【[Offer收割]编程练习赛12 A】歌德巴赫猜想
    【codeforces 779E】Bitwise Formula
    Java Web整合开发(85)
    数字
    T2602 最短路径问题 codevs
    P3378 堆【模板】 洛谷
    T1013 求先序排列 codevs
    P1717 钓鱼 洛谷
    P2085 最小函数值 洛谷
  • 原文地址:https://www.cnblogs.com/hwu2014/p/4460497.html
Copyright © 2011-2022 走看看