FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
coding-Interview/3Sum.java at master · arjunmullick/coding-Interview · GitHub
arjunmullick
/
coding-Interview
Public
Notifications
You must be signed in to change notification settings
Fork
1
Star
3
Code
Issues
0
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
coding-Interview
/
3Sum.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
34 lines (31 loc) · 1.22 KB
Breadcrumbs
coding-Interview
/
3Sum.java
Copy path
File metadata and controls
34 lines (31 loc) · 1.22 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class
Solution
{
public
List
<
List
<
Integer
>>
threeSum
(
int
[]
nums
) {
List
<
List
<
Integer
>>
result
=
new
ArrayList
<>();
int
n
=
nums
.
length
;
if
(
n
==
0
)
return
result
;
Arrays
.
sort
(
nums
);
for
(
int
p1
=
0
;
p1
<
n
-
2
;
p1
++){
if
(
p1
>
0
&&
nums
[
p1
-
1
] ==
nums
[
p1
])
continue
;
// if we do not want duplicates
int
l
=
p1
+
1
;
int
r
=
n
-
1
;
while
(
l
<
r
){
int
sum
=
nums
[
l
] +
nums
[
r
] +
nums
[
p1
];
if
(
sum
==
0
){
// 0 is the target sum
List
<
Integer
>
list
=
new
ArrayList
<>();
list
.
add
(
nums
[
p1
]);
list
.
add
(
nums
[
l
]);
list
.
add
(
nums
[
r
]);
result
.
add
(
list
);
while
(
l
<
r
&&
nums
[
l
] ==
nums
[
l
+
1
])
l
++;
//skip same
while
(
l
<
r
&&
nums
[
r
] ==
nums
[
r
-
1
])
r
--;
//skip same
}
if
(
sum
<
0
){
l
++;
}
else
{
//always consume one element even when sum == 0
r
--;
}
}
}
return
result
;
}
}
Back
|
FazBrowse Home
|
New Git URL