Python Solution one O (n^3) time complexity does not meet the requirements, the violence of the United States is still very intuitive:
"" "Programmer:eofdate:2015.04.11file:3sum.pye-mail: [email protected]description: This is the first version of which I used and try to solve3sum problem. It's work correctly but has a bad time complexity. "" " Class Solution: # @return A list of lists of Length3, [[Val1, Val2, val3]] ret_list = [] def threesum (self, num): length = Len (num) for I in range (0, length): For j in range (i+1, length): For K I N Range (j+1, length): if num[i] + num[j] + num[k] = = 0: TMP = Self.sequence (Num[i], num[j], num[k]) if Self.same_solution (TMP) is True: Continue else:self.ret_list + = [tmp] return Self.ret_lis t # make sure the @self. Ret_list E1 < E2 < E3 def sequence (self, A, B, c): ret = [] If a < ; B:ifA < C:ret + = [a] if b < C:ret + = [B, c] else: RET + = [C, b] Else:ret + = [C, a, b] else: # a > B in this situation If b < C:ret + = [b] If a < C:ret + = [A, c] Else:ret + = [C, a] else:ret + = [C, B, a] return ret def same_so Lution (self, SV): If Len (self.ret_list)! = 0:row = Len (self.ret_list) col = Len (self.ret_li St[0]) for I in range (0, Row): for J in range (0, col): if SELF.RET_LIST[I][J] ! = Sv[j]: break; If j = = Col-1: return True return false#-------------just for testing----------s = solution () D ate = [-1, 0, 1, 2,-1, -4]print s.threesum (Date)
Answer two:
I just want to say ... This is already the fourth version (#‵′)
...
Will find the code a lot shorter, but there is still no time complexity.
I used two hash tables,
The ret_dic in the back is to avoid repeated answers.
"" "Programmer:eofdate:2015.04.11file:3sum_opt_3.pye-mail: [Email protected]descrip Tion:this is the #fourth # version which I used and try to solve3sum problem. I used dictionary and try to improve the performance. It's work correctly but also has a bad time complexity. "" " Class Solution: # @return A list of lists of Length3, [[Val1, Val2, val3]] ret_list = [] dic = {} Ret_dic = {} def threesum (self, num): length = Len (num) # Initialize the @dic and @time for I in range (0, Length): If num[i] not in self.dic:self.dic[num[i]] = Num[i] Num.sort () # Kernel Part of the algorithm for I in range (0, length): For j in range (i + 1, length): #It ' s a old trick to use the inverse number as the index if-(Num[i] + num[j]) in Self.dic: If-(Num[i] + num[j]) <= Num[i]: TMP = [-(Num[i] + num[j]), Num[i], Num[j]] elif-(Num[i] + num[j]) >= Num[j]: TMP = [Num[i], Num[j],-(Num[i] + num[j])] else:tmp = [nu M[i],-(Num[i] + num[j]), NUM[J]] if STR (TMP) not in self.ret_dic:self.ret_dic[ STR (TMP)] = tmp for i in self.ret_dic:self.ret_list + = [Self.ret_dic[i]] return self.ret_list#-- -----------just for testing----------s = solution () date = [-1, 0, 1, 2,-1, -4]print s.threesum (date) date = [4,4,3,-5,0, 0,0,-2,3,-5,-5,0]print S.threesum (Date)
Python Solution Three:
None of the previous two solutions can be used ... Only this one can be AC.
Solution Two may be time-consuming when constructing dictionary, so there is a problem with the complexity of times.
Class Solution: # @return A list of lists of length 3, [[Val1,val2,val3]] def threesum (self, num): If Len (num ) <= 2:return [] ret = [] tar = 0 Num.sort () i = 0 while i < len (num) -2:j = i + 1 k = len (num)-1 while J < K:if Num[i] + num[j] + num[ K] < Tar:j + = 1 elif num[i] + num[j] + num[k] > tar:k-= 1 Else:ret.append ([Num[i], num[j], Num[k]]) J + = 1 k -= 1 # folowing 3 while can avoid the duplications while J < K and num[j] = = num[ J-1]: J + = 1 while J < K and num[k] = = num[k + 1]: K -= 1 While i < Len (num)-2 and num[i] = = num[i + 1]: i + = 1 i + = 1 return Ret
The Java answer to the Triumph charge:
Package _3sum;import Java.util.arrays;import Java.util.linkedlist;import Java.util.list;public class Solution {public List<list<integer>> threesum (int[] num) {arrays.sort (num); list<list<integer>> result = new linkedlist<> (); for (int i = num.length-1; i > 1; i--) {if (i + 1 & Lt Num.length && num[i] = = num[i + 1]) {continue;} for (int j = 0, k = i-1; j < K;) {int sum = Num[j] + num[k] + num[i];if (Sum < 0) {j + +;} else if (Sum > 0) {k--;} else {Result.add (arrays.aslist (num[ J], Num[k], num[i]));d o {j++;k--;} while (J < k && Num[j-1] = = Num[j] && num[k] = = num[k + 1]);}} return result;} public static void Main (string[] args) {System.out.println (New solution (). Threesum (new int[]{0, 0, 0, 0, 0, 0, 0}));}}
The C + + of Hao God
Skip to content this repositoryexploregistbloghelp@jasonleaster jasonleaster unwatch 2 Star 0 Fork 920penguiner/leetcode -1forked from Haoel/leetcode branch:master Leetcode-1/src/3sum/3sum.cpp@haoelhaoel in Oct Add comments to Explai n the solutions1 contributorrawblamehistory 188 lines (166 sloc) 5.134 kb//source:https://oj.leetcode.com/problems/ 3sum///Author:hao chen//date:2014-07-22/*********************************************************************** * * 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, 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) * * ******************************************* **********************/#include <stdio.h> #include <iostream> #include <vector> #include <set># Include <algorithm>using namespace std;/* * simlar like "number of" problem, we can have the simlar solution. * * Suppose the input array is s[0..n-1], 3SUM can solved in O (n^2) time on average by * inserting each number s[i ] into a hash table, and then for each index I and j, * Checking whether the hash table contains the integer-(s[i]+s [j]) * * Alternatively, the algorithm below first sorts the input array and then tests all * possible pairs in a care Ful order that avoids the need-binary search for the pairs * in the sorted list, achieving worst-case O (n^n) * * S olution:quadratic algorithm * Http://en.wikipedia.org/wiki/3SUM * */vector<vector<int> > Threesum (vector& Lt;int> &num) {vector< vector<int> > result; Sort the array, this is the key sort (Num.begin (), Num.end ()); int n = num.size (); for (int i=0; i<n-2; i++) {//skip the duplication if (i>0 && num[i-1]==num[i]) continue; int a = Num[i]; int low = i+1; int high = n-1; while (Low < high) {int b = num[low]; int c = Num[high]; if (A+b+c = = 0) {//got the soultion vector<int> v; V.push_back (a); V.push_back (b); V.push_back (c); Result.push_back (v); Continue search for all triplet combinations summing to zero. Skip the duplication while (Low<n && num[low]==num[low+1]) low++; while (high>0 && num[high]==num[high-1]) high--; low++; high--; } else if (A+b+c > 0) {//skip the duplication while (high>0 && num[high]==num[ HIGH-1]) high--; high--; } else{//skip the duplication while (Low<n && num[low]==num[low+1]) low++; low++; }}} return result; Using combination method could meet <<time Limit exceeded>> errorvector<vector<int> > Combination (vector<int> &v, int k); bool Issumzero (vector<int>& v); int sum (vector<int>& V);vector<vector<int> > threeSum2 (vector<int> &num) {vector< vector<int> > result; vector< vector<int> > R = combination (num, 3); for (int i=0; i<r.size (); i++) {if (Issumzero (R[i])) {result.push_back (r[i]); }} return result; BOOL Issumzero (vector<int>& v) {return sum (v) ==0;} int sum (vector<int>& v) {int s=0; for (int i=0; i<v.size (); i++) {s + = v[i]; } return s;} vector<vector<int> > combination (vector<int> &v, int k) {vector<vector<int> > result; Vector<int> D; int n = v.size (); for (int i=0; i<n; i++) {d.push_back ((i<k)? 1:0); }//1) from the left, find the [1,0] pattern, change it to [0,1]//2) Move all of the 1 before the pattern to the MO St left side//3) Check all of 1 moves to the right while (1) {vector<int> tmp; for (int x=0; x<n; x + +) {if (d[x]) tmp.push_back (v[x]); } sort (Tmp.begin (), Tmp.end ()); Result.push_back (TMP); Step 1), find [1,0] pattern int i; BOOL found = false; int ones = 0; for (i=0; i<n-1; i++) {if (d[i]==1 && d[i+1]==0) {d[i]=0; d[i+1]=1; Found = true; Step 2) Move all of right 1 to the most left side for (int j=0; j<i; J + +) {d[j]= (o NES > 0)? 1:0; ones--; } break; } if (d[i]==1) ones++; } if (!found) {break; }} return result; void Printmatrix (Vector<vector<int> > &matrix) {for (int i=0; i<matrix.size (); i++) {printf ("{ "); for (int j=0; j< matrix[i].size (); j + +) {printf ("%3d", Matrix[i][j]); } printf ("}\n"); } cout << Endl;} int main () {//int a[] = {-1, 0, 1, 2,-1, 1,-4}; int a[] = {-1, 1, 1, 1,-1,-1, 0,0,0}; Vector<int> N (A, a+sizeof (a)/sizeof (int)); vector< vector<int> > result = Threesum (n); Printmatrix (result); return 0;} Status API Training Shop Blog about©2015 GitHub, Inc. Terms Privacy Security Contact
Leetcode # 3Sum #