zoukankan      html  css  js  c++  java
  • 015 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: 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]
    ]
    详见:https://leetcode.com/problems/3sum/description/
    实现语言:Java
    class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            int target=0;
            List<List<Integer>> res=new ArrayList<List<Integer>>();
            int size=nums.length;
            if(size<3||nums==null){
                return res;
            }
            Arrays.sort(nums);
            for(int i=0;i<size-2;++i){
                if(i>0&&nums[i]==nums[i-1]){
                    continue;
                }
                int l=i+1;
                int r=size-1;
                while(l<r){
                    int sum=nums[i]+nums[l]+nums[r];
                    if(sum<target){
                        while(l<r&&nums[++l]==nums[l-1]);
                    }else if(sum>target){
                        while(l<r&&nums[--r]==nums[r+1]);
                    }else{
                        List<Integer> tmp=new ArrayList<Integer>();
                        tmp.add(nums[i]);
                        tmp.add(nums[l]);
                        tmp.add(nums[r]);
                        res.add(tmp);
                        while(l<r&&nums[++l]==nums[l-1]);
                        while(l<r&&nums[--r]==nums[r+1]);
                    }
                }
            }
            return res;
        }
    }
    
  • 相关阅读:
    centos 6.5 添加静态ip
    质数因子
    sizeof 和 strlen 的区别
    C++输入带空格的字符串
    字符集合
    汽水瓶
    算法汇总
    Word目录生成
    0-1背包问题的动态规划法与回溯法
    vue父元素调用子组件的方法报undefined
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8479819.html
Copyright © 2011-2022 走看看