当前位置: 面试刷题>> 两数和的最接近值 (经典算法题500道)
### 题目描述补充
给定一个整数数组`nums`和一个目标值`target`,请你在该数组中找出两个数,使得它们的和与目标值`target`的差的绝对值最小。返回这两个数的索引值(索引值从0开始),如果有多个答案存在,则返回任意一对即可。
### 示例
**输入**:
- `nums = [2, 7, 11, 15]`
- `target = 9`
**输出**:
- `[0, 1]` (因为`2 + 7 = 9`,是数组中两数之和最接近目标值`9`的组合,且索引为`[0, 1]`)
### PHP 示例代码
```php
function twoSumClosest($nums, $target) {
$n = count($nums);
$closestDiff = PHP_INT_MAX;
$result = [-1, -1];
for ($i = 0; $i < $n; $i++) {
for ($j = $i + 1; $j < $n; $j++) {
$diff = abs($nums[$i] + $nums[$j] - $target);
if ($diff < $closestDiff) {
$closestDiff = $diff;
$result = [$i, $j];
}
}
}
return $result;
}
// 示例用法
$nums = [2, 7, 11, 15];
$target = 9;
$result = twoSumClosest($nums, $target);
print_r($result);
```
### Python 示例代码
```python
def twoSumClosest(nums, target):
n = len(nums)
closest_diff = float('inf')
result = [-1, -1]
for i in range(n):
for j in range(i + 1, n):
diff = abs(nums[i] + nums[j] - target)
if diff < closest_diff:
closest_diff = diff
result = [i, j]
return result
# 示例用法
nums = [2, 7, 11, 15]
target = 9
result = twoSumClosest(nums, target)
print(result)
```
### JavaScript 示例代码
```javascript
function twoSumClosest(nums, target) {
let n = nums.length;
let closestDiff = Infinity;
let result = [-1, -1];
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
let diff = Math.abs(nums[i] + nums[j] - target);
if (diff < closestDiff) {
closestDiff = diff;
result = [i, j];
}
}
}
return result;
}
// 示例用法
const nums = [2, 7, 11, 15];
const target = 9;
const result = twoSumClosest(nums, target);
console.log(result);
```
### 码小课提示
以上代码示例通过双重循环遍历数组,计算每两个数的和与目标值的差的绝对值,并更新最小差值及其对应的索引。虽然这种方法在理解上较为直观,但时间复杂度较高(O(n^2)),对于大数据集可能不够高效。码小课网站中分享了更多关于算法优化的内容,如哈希表等数据结构的应用,可以显著提高解决此类问题的效率。