forked from alexkoby/Leetcode-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3Sum Closest
More file actions
25 lines (24 loc) · 1008 Bytes
/
3Sum Closest
File metadata and controls
25 lines (24 loc) · 1008 Bytes
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
//Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target.
//Return the sum of the three integers. You may assume that each input would have exactly one solution.
//Brute forced it
class Solution {
public int threeSumClosest(int[] nums, int target) {
int closestSum = nums[0] + nums[1] + nums[2];
System.out.println(closestSum);
for(int i = 0; i < nums.length - 2; i++)
{
for(int j = i + 1; j < nums.length - 1; j++)
{
for(int k = j + 1; k < nums.length; k++)
{
if(Math.abs(nums[i] + nums[j] + nums[k] - target) < Math.abs(closestSum - target))
{
closestSum = nums[i] + nums[j] + nums[k];
System.out.println(nums [i] + " " + nums[j] + " " + nums[k]);
}
}
}
}
return closestSum;
}
}