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.Example 1:
Input: nums = {-1,2,1,-4}, target = 1 Output: 2
Approach
Java
import java.util.Arrays;public class ThreeSumClosest {public static void main(String[] args) {int nums[] = { -1, 2, 1, -4 };int target = 1;System.out.println(threeSumClosest(nums, target));}static int threeSumClosest(int[] nums, int target) {int n = nums.length;int res = 0;if (n < 3)return res;Arrays.sort(nums);int max1 = Integer.MAX_VALUE;for (int i = 0; i < n - 2; i++) {int low = i + 1, high = n - 1;while (low < high) {if (Math.abs(target - (nums[i] + nums[low] + nums[high])) < max1) {max1 = Math.abs(target - (nums[i] + nums[low] + nums[high]));res = nums[i] + nums[low] + nums[high];}if (nums[i] + nums[low] + nums[high] > target)high--;elselow++;}}return res;}}
C++
#include <bits/stdc++.h>using namespace std;int threeSumClosest(vector<int>& nums, int target){int n=nums.size();int res=0;if(n<3)return res;sort(nums.begin(),nums.end());int max1=INT_MAX;for(int i=0;i<n-2;i++){int low=i+1,high=n-1;while(low<high){if(abs(target-(nums[i]+nums[low]+nums[high]))<max1){max1=abs(target-(nums[i]+nums[low]+nums[high]));res=nums[i]+nums[low]+nums[high];}if(nums[i]+nums[low]+nums[high]>target)high--;elselow++;}}return res;}int main(){vector<int> nums ={-1,2,1,-4};int target = 1;cout<<threeSumClosest(nums,target);return 0;}
No comments:
Post a Comment