生活随笔
收集整理的這篇文章主要介紹了
【leetcode】3Sum
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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:
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) 先對數組進行排序,從頭開始掃描,掃描的數作為固定的數。 a=num[i]; 當固定了一個數以后, 選取b=num[i+1]=num[j] 選取c=num[n-1]=num[k] 若a+b+c=0 則找到了一個a,b,c,記錄下來,j++,k--繼續掃描 若a+b+c<0 則j++ 若a+b+c>0 則k-- 要注意去重的問題: 1.若num[i]=num[i-1],則跳過 2.若num[j]=num[j-1],則跳過 3.若num[k]=num[k+1],則跳過
1 class Solution {
2 public :
3 vector<vector<
int > > threeSum(vector<
int > &
num) {
4
5 int n=
num.size();
6 sort(num.begin(),num.end());
7
8 int i,j,k;
9 int a,b,c;
10 vector<vector<
int > >
result;
11
12 for (i=
0 ;i<n-
2 ;i++
)
13 {
14 j=i+
1 ;
15 k=n-
1 ;
16
17 while (j<
k)
18 {
19 a=
num[i];
20 if (i>
0 &&num[i]==num[i-
1 ])
21 {
22 break ;
23 }
24 b=
num[j];
25 if (j>i+
1 &&num[j]==num[j-
1 ])
26 {
27 j++
;
28 continue ;
29 }
30
31 c=
num[k];
32 if (k<n-
1 &&num[k]==num[k+
1 ])
33 {
34 k--
;
35 continue ;
36 }
37
38 if (a+b+c==
0 )
39 {
40 vector<
int > tmp(
3 );
41 tmp[
0 ]=
a;
42 tmp[
1 ]=
b;
43 tmp[
2 ]=
c;
44 result.push_back(tmp);
45 j++
;
46 k--
;
47 }
48 else if (a+b+c<
0 )
49 {
50 j++
;
51 }
52 else if (a+b+c>
0 )
53 {
54 k--
;
55 }
56 }
57 }
58
59 return result;
60
61 }
62 };
63 ?
轉載于:https://www.cnblogs.com/reachteam/p/4190319.html
總結
以上是生活随笔 為你收集整理的【leetcode】3Sum 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。