Leetcode-the closest sum of three problems

topic:

Given an array of n integers nums and a target value target. Find the three integers in nums so that their sum is closest to target. Returns the sum of these three numbers. Assume that there is only one answer for each set of inputs.

Example:

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The closest sum to target is 2 (-1 + 2 + 1 = 2).

Ideas:

  1. The overall idea is the same as the sum of three numbers in the previous article, and the idea of sorting + double pointer is still adopted .
  2. The sum of a+b+c is required to be the closest to target, then let x=a+b+c-target, and what we require is the value of x that is closest to 0.
  3. Set an initial comparison value temp, which may be the sum of the first three numbers in the nums array after sorting minus target:, num[1]+num[2]+num[3]-targetthen you only need to pass Math.abs()the absolute value comparison method to take the absolute minimum value.

code show as below:
Insert picture description here

Test Results:
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_41570890/article/details/109225599