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:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        int res = nums[0] + nums[1] + nums[2];
        for(int i = 0; i < nums.size() - 2; ++i) {
            int low = i+1;
            int high = nums.size() - 1;
            while(low < high) {
                int cur_sum = nums[i] + nums[low] + nums[high];
                if (abs(cur_sum-target) < abs(res-target)) res = cur_sum;
                if (cur_sum == target) {
                    return target;
                } else if (cur_sum > target) {
                    high--;
                } else if (cur_sum < target) {
                    low++;
                }
            }
        }
        return res;
    }
};

 

 

 

 

 1 class Solution {
 2     public int threeSumClosest(int[] nums, int target) {
 3         int res = nums[0]+nums[1]+nums[2];
 4         Arrays.sort(nums);
 5         for(int i = 0 ; i<nums.length-2;i++){
 6             int lo=i+1,hi=nums.length-1;
 7             while(lo<hi){
 8                 int sum=nums[i]+nums[lo]+nums[hi];
 9                 if(sum>target) hi--;
10                 else lo++;
11                 if(Math.abs(sum-target)<Math.abs(res-target))
12                     res = sum;
13             }
14         }
15         return res;
16     }
17 }

 

相关文章:

  • 2021-07-10
  • 2021-08-22
  • 2021-12-20
  • 2021-06-28
  • 2021-08-21
  • 2021-09-25
  • 2022-02-18
  • 2021-09-30
猜你喜欢
  • 2021-11-06
  • 2021-08-17
  • 2021-05-20
相关资源
相似解决方案