Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitbafff47

Browse files
author
applewjg
committed
3 Sum
Change-Id: Ie4238a871e4082637c8430d1c00f390a26933b1c
1 parent98f9fe7 commitbafff47

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

‎3Sum.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 20, 2014
4+
Problem: 3Sum
5+
Difficulty: Medium
6+
Source: https://oj.leetcode.com/problems/3sum/
7+
Notes:
8+
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
9+
Find all unique triplets in the array which gives the sum of zero.
10+
Note:
11+
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a <= b <= c)
12+
The solution set must not contain duplicate triplets.
13+
For example, given array S = {-1 0 1 2 -1 -4},
14+
A solution set is:
15+
(-1, 0, 1)
16+
(-1, -1, 2)
17+
18+
Solution: Simplify '3sum' to '2sum' O(n^2). http://en.wikipedia.org/wiki/3SUM
19+
*/
20+
publicclassSolution {
21+
publicList<List<Integer>>threeSum(int[]num) {
22+
List<List<Integer>>res =newArrayList<List<Integer>>();
23+
Arrays.sort(num);
24+
intN =num.length;
25+
for (inti =0;i <N-2 &&num[i] <=0; ++i)
26+
{
27+
if (i >0 &&num[i] ==num[i-1])
28+
continue;// avoid duplicates
29+
inttwosum =0 -num[i];
30+
intl =i +1,r =N -1;
31+
while (l <r)
32+
{
33+
intsum =num[l] +num[r];
34+
if (sum <twosum) ++l;
35+
elseif (sum >twosum) --r;
36+
else {
37+
ArrayList<Integer>tmp =newArrayList<Integer>();
38+
tmp.add(num[i]);tmp.add(num[l]);tmp.add(num[r]);
39+
res.add(tmp);
40+
++l; --r;
41+
while (l <r &&num[l] ==num[l-1]) ++l;// avoid duplicates
42+
while (l <r &&num[r] ==num[r+1]) --r;// avoid duplicates
43+
}
44+
}
45+
}
46+
returnres;
47+
}
48+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp