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

    public class Solution {
        public List<List<Integer>> threeSum(int[] num) {
           List<List<Integer> > result = new ArrayList<List<Integer> >();
    		Arrays.sort(num);
    		int length = num.length;
    		if(length >= 3) {
    			for(int i = 0; i < length - 2 && num[i] <= 0; ++i) {
    				int start = i + 1, end = length - 1;				
    				//find all solution starting with num[i]
    				while(start < end){
    					int sum = num[i] + num[start] + num[end];
    					if(sum < 0) //num[start] is too small
    						++start;
    					else if(sum > 0) //num[end] is too large
    						--end;
    					else { //find a solution
    						List<Integer> oneSolution = new ArrayList<Integer>();
    						oneSolution.add(num[i]);
    						oneSolution.add(num[start]);
    						oneSolution.add(num[end]);
    						result.add(oneSolution);
    						//remove the duplicates 
    						do{
    							++start;
    						}while(start < end && num[start - 1] == num[start]);
    						do{
    							--end;
    						}while(start < end && num[end] == num[end + 1]);
    					}
    				}
    				//remove the duplicates of num[i] since we have found all solutions 
    				//staring with num[i].
    				while(i + 1 < length - 2 && num[i] == num[i + 1])
    					++i;
    			}
    		}
    		return result;
        }
    }
    

      

      

  • 相关阅读:
    LeetCode 461. Hamming Distance
    LeetCode 442. Find All Duplicates in an Array
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode Find the Difference
    LeetCode 415. Add Strings
    LeetCode 445. Add Two Numbers II
    LeetCode 438. Find All Anagrams in a String
    LeetCode 463. Island Perimeter
    LeetCode 362. Design Hit Counter
    LeetCode 359. Logger Rate Limiter
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3617044.html
Copyright © 2011-2022 走看看