当前位置: 面试刷题>> 最接近target的值 (经典算法题500道)
**题目描述**:
给定一个整数数组 `nums` 和一个目标值 `target`,找出数组中所有元素与目标值的差的绝对值中最小的那个元素,并返回该元素。如果存在多个这样的元素,则返回任意一个即可。
**示例 1**:
```
输入: nums = [1,2,3,4], target = 2.7
输出: 3
解释: |3 - 2.7| = 0.3 是所有差值中最小的。
```
**示例 2**:
```
输入: nums = [1], target = 0
输出: 1
解释: |1 - 0| = 1 是唯一可能的差值。
```
**PHP 代码示例**:
```php
function findClosestValue($nums, $target) {
$minDiff = PHP_INT_MAX;
$closestNum = null;
foreach ($nums as $num) {
$diff = abs($num - $target);
if ($diff < $minDiff) {
$minDiff = $diff;
$closestNum = $num;
}
}
return $closestNum;
}
// 示例使用
$nums = [1, 2, 3, 4];
$target = 2.7;
$result = findClosestValue($nums, $target);
echo "最接近target的值是: " . $result;
```
**Python 代码示例**:
```python
def findClosestValue(nums, target):
min_diff = float('inf')
closest_num = None
for num in nums:
diff = abs(num - target)
if diff < min_diff:
min_diff = diff
closest_num = num
return closest_num
# 示例使用
nums = [1, 2, 3, 4]
target = 2.7
result = findClosestValue(nums, target)
print("最接近target的值是:", result)
```
**JavaScript 代码示例**:
```javascript
function findClosestValue(nums, target) {
let minDiff = Infinity;
let closestNum = null;
nums.forEach(num => {
const diff = Math.abs(num - target);
if (diff < minDiff) {
minDiff = diff;
closestNum = num;
}
});
return closestNum;
}
// 示例使用
const nums = [1, 2, 3, 4];
const target = 2.7;
const result = findClosestValue(nums, target);
console.log("最接近target的值是:", result);
```
以上代码示例展示了如何在 PHP、Python 和 JavaScript 中解决这个算法问题。通过遍历数组中的每个元素,计算它与目标值的差的绝对值,并追踪最小的差值及对应的元素。最后返回这个最接近目标值的元素。