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

Commitebc8eaf

Browse files
MEDIUM/src/medium/_3SumClosest.java
1 parent0f3d16c commitebc8eaf

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

‎MEDIUM/src/medium/_3SumClosest.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
packagemedium;
2+
3+
importjava.util.Arrays;
4+
5+
publicclass_3SumClosest {
6+
/**One implicit requirement is that you must have THREE elements!!! You cannot have just one!*/
7+
8+
/**Another cool trick that I learned here is that:
9+
* after comparing the absolute difference, we'll see if thisSum > target or not, then we decide to shift left or right pointer.*/
10+
11+
12+
publicintthreeSumClosest(int[]nums,inttarget) {
13+
if(nums ==null ||nums.length ==0)return0;
14+
Arrays.sort(nums);
15+
intlen =nums.length;
16+
if(len <3){
17+
intsum =0;
18+
for(inti :nums){
19+
sum +=i;
20+
}
21+
returnsum;
22+
}
23+
intsum =nums[0] +nums[1] +nums[2];
24+
for(inti =0;i <nums.length-2;i++){
25+
intleft =i+1,right =nums.length-1;
26+
while(left <right){
27+
intthisSum =nums[i] +nums[left] +nums[right];
28+
if(Math.abs(target -thisSum) <Math.abs(target -sum)) {
29+
sum =thisSum;
30+
if(sum ==target)returnsum;
31+
}
32+
elseif(target >thisSum){
33+
left++;
34+
}else {
35+
right--;
36+
}
37+
}
38+
}
39+
returnsum;
40+
}
41+
42+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp