FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode-algorithms/src/ThreeSumClosest.java at master · anishLearnsToCode/leetcode-algorithms · GitHub
anishLearnsToCode
/
leetcode-algorithms
Public
Notifications
You must be signed in to change notification settings
Fork
17
Star
98
Code
Issues
0
Pull requests
0
Discussions
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode-algorithms
/
src
/
ThreeSumClosest.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
28 lines (25 loc) · 883 Bytes
Breadcrumbs
leetcode-algorithms
/
src
/
ThreeSumClosest.java
Copy path
File metadata and controls
28 lines (25 loc) · 883 Bytes
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
// https://leetcode.com/problems/3sum-closest
// T: O(n^2)
// S: O(1)
import
java
.
util
.
Arrays
;
public
class
ThreeSumClosest
{
public
static
void
main
(
String
[]
args
) {
System
.
out
.
println
(
threeSumClosest
(
new
int
[] {
0
,
2
,
1
, -
3
},
1
));
}
public
static
int
threeSumClosest
(
int
[]
nums
,
int
target
) {
Arrays
.
sort
(
nums
);
int
closestSum
=
nums
[
0
] +
nums
[
1
] +
nums
[
2
];
for
(
int
i
=
0
;
i
<
nums
.
length
-
2
;
i
++) {
for
(
int
j
=
i
+
1
,
k
=
nums
.
length
-
1
;
j
<
k
; ) {
int
sum
=
nums
[
i
] +
nums
[
j
] +
nums
[
k
];
if
(
sum
==
target
)
return
sum
;
if
(
Math
.
abs
(
sum
-
target
) <
Math
.
abs
(
closestSum
-
target
)) {
closestSum
=
sum
;
}
else
if
(
sum
>
target
)
k
--;
else
j
++;
}
}
return
closestSum
;
}
}
Back
|
FazBrowse Home
|
New Git URL