FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode/code/lc16.java at master · mJackie/leetcode · GitHub
mJackie
/
leetcode
Public
Notifications
You must be signed in to change notification settings
Fork
135
Star
405
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode
/
code
/
lc16.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
29 lines (28 loc) · 870 Bytes
Breadcrumbs
leetcode
/
code
/
lc16.java
Copy path
File metadata and controls
29 lines (28 loc) · 870 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
29
package
code
;
import
java
.
util
.
Arrays
;
/*
* 16. 3Sum Closest
* 题意:找出3个数的和最接近target
* 难度:Medium
* 分类:Array, Two Pointers
* 思路:3sum的思路,每次记下最接近的res即可
* Tips:lc15, lc16, lc923
*/
public
class
lc16
{
public
int
threeSumClosest
(
int
[]
nums
,
int
target
) {
int
res
=
nums
[
0
]+
nums
[
1
]+
nums
[
2
];
Arrays
.
sort
(
nums
);
for
(
int
i
=
0
;
i
<
nums
.
length
-
2
;
i
++) {
int
start
=
i
+
1
;
int
end
=
nums
.
length
-
1
;
while
(
start
<
end
){
int
sum
=
nums
[
i
] +
nums
[
start
] +
nums
[
end
];
if
(
sum
==
target
)
return
target
;
else
if
(
sum
<
target
)
start
++;
else
if
(
sum
>
target
)
end
--;
if
(
Math
.
abs
(
sum
-
target
)<
Math
.
abs
(
res
-
target
))
res
=
sum
;
}
}
return
res
;
}
}
Back
|
FazBrowse Home
|
New Git URL