zoukankan      html  css  js  c++  java
  • LeetCode -- 3Sum

    Question:

    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)

    Analysis:

    在sum系列中,这是最后做的一道,用前面的方法却错误多多,很是烦恼。

    2sum中,使用了两种方法,暴力求解(2层for循环)和使用Hashmap的方法;

    3sum中,使用2个指针分别指向最大和最小值,同时要查重,避免重复的三元组放入list中。

    3Sum Closet中,用两个变量记录当前sum和sum与target间的差距,而无需去重检验,总体思路同3Sum。

    4sum中,使用两个for循环和2个指针,分别指向最大和最小的值,然后用HashSet纪录选择过的四元组。

    Answer:

    public class Solution {
            private List<List<Integer>> res;
        public List<List<Integer>> threeSum(int[] nums) {
            res = new ArrayList<List<Integer>> ();
            Arrays.sort(nums);
            
            
            for(int i=0; i<=nums.length-3; i++) {
                    if(i!=0 && nums[i] == nums[i-1])
                        continue;
                    deal(nums, i, i+1, nums.length-1);
            }
            return res;
        }
        
        public void deal(int[] nums, int i, int p, int q) {
            while(p<q) {
                if(nums[p] + nums[q] + nums[i] > 0) {
                    q--;
                }
                else if(nums[p] + nums[q] + nums[i] < 0) {
                    p++;
                }
                else {
                    List<Integer> li = new ArrayList<Integer> ();
                    li.add(nums[i]);
                    li.add(nums[p]);
                    li.add(nums[q]);
                    res.add(li);
                    p++;
                    q--;
                    while(p<q && nums[p]==nums[p-1]) {
                        p++;
                    }
                    while(p<q && nums[q]== nums[q+1]) {
                        q--;
                    }
                }
            }
            
        }
    }
  • 相关阅读:
    2014华为员工年终奖及年薪盘点
    Gradle命令行黑魔法
    委托的那些事
    动态代理
    音乐播放
    Eclipse plugin web site 发布和版本更新
    JavaScript—之对象参数的引用传递
    Bootstrap 3 How-To #1 下载与配置
    代码审计和漏洞挖掘的思路
    核心C#
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4789279.html
Copyright © 2011-2022 走看看