Leetcode #15 3Sum (M)

Source: Internet
Author: User

[Problem]

Given an array S of n integers, is 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 is in non-descending order. (ie, abc)
    • 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]

The main point of this question is the two requirements in the note, which can be sorted out. After sorting, first put forward a number and then use 2Sum to solve. Note that you should skip the numbers that have been used. The overall complexity is O (NLOGN) + O (n*n) = O (n*n).

[Solution]

Importjava.util.ArrayList;Importjava.util.Arrays;Importjava.util.List; Public classSolution { PublicList<list<integer>> Threesum (int[] num) {List<List<Integer>> solution =NewArraylist<list<integer>>(); if(Num.length < 3) {            returnsolution;                } arrays.sort (num); inttarget = 0;  for(inti = 0; i < num.length-2; i++) {            if(i > 0 && num[i] = = Num[i-1]) {                Continue;//If current value is already tested as the first element, skip;            }                        //Do 2Sum            intHead = i + 1; intTail = num.length-1;  while(Head <tail) {                if(Head > i + 1 && num[head] = = Num[head-1]) {head++; Continue;//If current value is already tested as the second, skip;                }                                if(Tail < num.length-1 && Num[tail] = = Num[tail + 1]) {tail--; Continue;//similar test for the third element                }                                intsum = Num[i] + Num[head] +Num[tail]; if(Sum = =target) {Solution.add (NewArraylist<integer>(Arrays.aslist (Num[i], Num[head], num[tail])); Head++; Tail--; } Else if(Sum >target) {Tail--; } Else{Head++; }            }        }                returnsolution; }}

Leetcode #15 3Sum (M)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.