16. 3Sum Closest 最接近的三数之和:多语言实现与分析
一、题目分析
给定一个包含 n 个整数的数组 nums 和一个目标整数 target,需在数组中找出三个整数,使得它们的和最接近 target,并返回这个最接近的和。假设每个输入都恰好有一个解决方案。
二、常用解法
排序 + 双指针法
- 思路:
- 首先对数组
nums进行排序,这一步是后续双指针法高效执行的基础。排序后数组元素按升序排列,方便根据和与目标值的比较结果移动指针。 - 遍历排序后的数组,对于每个元素
nums[t],使用双指针法在剩余元素中寻找最接近目标值的组合。初始化左指针i为t + 1,右指针j为数组末尾。 - 计算当前三个数的和
_sum = nums[t] + nums[i] + nums[j],并比较_sum与target的差值的绝对值和当前记录的最接近和res与target的差值的绝对值。若_sum更接近target,则更新res。 - 根据
_sum与target的大小关系移动指针:若_sum > target,说明和偏大,将右指针j向左移动,以减小和;若_sum < target,说明和偏小,将左指针i向右移动,以增大和;若_sum == target,则直接返回target,因为这是最接近的情况。 - 继续遍历数组,重复上述过程,直到遍历完整个数组。
- 首先对数组
- 优点:排序操作时间复杂度为 (O(n \log n)),后续双指针遍历时间复杂度为 (O(n^2)),总体时间复杂度为 (O(n^2)),相较于暴力解法的 (O(n^3)) 有显著提升。这种方法通过排序和双指针的巧妙结合,有效地减少了需要检查的组合数量,提高了查找效率。
三、多语言实现
Python实现
class Solution:
def threeSumClosest(self, nums, target):
N = len(nums)
nums.sort()
res = float('inf')
for t in range(N):
i, j = t + 1, N - 1
while i < j:
_sum = nums[t] + nums[i] + nums[j]
if abs(_sum - target) < abs(res - target):
res = _sum
if _sum > target:
j -= 1
elif _sum < target:
i += 1
else:
return target
return res
Java实现
import java.util.Arrays;
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int res = nums[0] + nums[1] + nums[2];
int n = nums.length;
for (int t = 0; t < n; t++) {
int i = t + 1;
int j = n - 1;
while (i < j) {
int sum = nums[t] + nums[i] + nums[j];
if (Math.abs(sum - target) < Math.abs(res - target)) {
res = sum;
}
if (sum > target) {
j--;
} else if (sum < target) {
i++;
} else {
return target;
}
}
}
return res;
}
}
C实现
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// 比较函数,用于qsort排序
int compare(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
int threeSumClosest(int *nums, int numsSize, int target) {
qsort(nums, numsSize, sizeof(int), compare);
int res = nums[0] + nums[1] + nums[2];
for (int t = 0; t < numsSize; t++) {
int i = t + 1;
int j = numsSize - 1;
while (i < j) {
int sum = nums[t] + nums[i] + nums[j];
if (fabs(sum - target) < fabs(res - target)) {
res = sum;
}
if (sum > target) {
j--;
} else if (sum < target) {
i++;
} else {
return target;
}
}
}
return res;
}
C++实现
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int res = nums[0] + nums[1] + nums[2];
int n = nums.size();
for (int t = 0; t < n; t++) {
int i = t + 1;
int j = n - 1;
while (i < j) {
int sum = nums[t] + nums[i] + nums[j];
if (abs(sum - target) < abs(res - target)) {
res = sum;
}
if (sum > target) {
j--;
} else if (sum < target) {
i++;
} else {
return target;
}
}
}
return res;
}
};
Go实现
package main
import (
"fmt"
"math"
"sort"
)
func threeSumClosest(nums []int, target int) int {
sort.Ints(nums)
res := nums[0] + nums[1] + nums[2]
for t := 0; t < len(nums); t++ {
i, j := t + 1, len(nums) - 1
for i < j {
sum := nums[t] + nums[i] + nums[j]
if math.Abs(float64(sum - target)) < math.Abs(float64(res - target)) {
res = sum
}
if sum > target {
j--
} else if sum < target {
i++
} else {
return target
}
}
}
return res
}
四、算法复杂性分析
时间复杂度
排序操作的时间复杂度为 (O(n \log n)),其中 n 是数组的长度。后续的双指针遍历,对于每个元素(最多 n 个),双指针移动的次数最多为 n 次,所以这部分的时间复杂度为 (O(n^2))。总体时间复杂度为 (O(n^2)),因为 (O(n^2)) 的增长速度快于 (O(n \log n))。
空间复杂度
除了输入数组外,使用的额外空间主要是常数级别的变量(如指针变量、存储最接近和的变量等),所以空间复杂度为 (O(1))。
五、实现的关键点和难度
关键点
- 排序的应用:排序是整个算法的关键起始步骤。通过排序,使得数组有序,为双指针法的高效应用奠定基础,方便根据和与目标值的大小关系移动指针。
- 双指针移动逻辑:根据当前三个数的和与目标值的比较结果,准确移动左右指针是找到最接近和的核心操作。如果和大于目标值,右指针左移以减小和;如果和小于目标值,左指针右移以增大和。
- 比较与更新:在遍历过程中,不断比较当前三个数的和与目标值的差值的绝对值和已记录的最接近和与目标值的差值的绝对值,并及时更新最接近和,确保最终返回的结果是最接近目标值的。
难度
- 边界条件处理:需要考虑数组为空、数组元素个数小于 3 等边界情况,确保算法在各种情况下都能正确运行。虽然题目假设每个输入都有解,但在实际实现中仍要对这些边界情况进行合理处理,以保证算法的鲁棒性。
- 优化细节:在实现过程中,要注意一些优化细节,例如如何避免不必要的计算。由于数组已排序,当移动指针时,可以利用这个特性跳过一些不可能产生更优解的情况,进一步提高算法效率。但这需要对算法有深入的理解和细致的思考。
六、扩展及难度加深题目
扩展题目1:四数最接近之和
给定一个包含 n 个整数的数组 nums 和一个目标整数 target,找出四个整数使得它们的和最接近 target。可以类比三数最接近之和的方法,在排序后通过嵌套双指针法来解决,时间复杂度可能达到 (O(n^3))。
扩展题目2:带权重的最接近三数之和
给数组中的每个元素赋予一个权重,要求找出三个元素,使得它们的加权和最接近 target。这需要在计算和以及比较接近程度时,考虑权重因素,增加了算法的复杂性。
难度加深题目1:动态更新数组的最接近三数之和
假设数组会动态更新(添加或删除元素),要求在每次更新后能够高效地重新计算最接近 target 的三数之和。这可能需要使用更复杂的数据结构(如平衡二叉搜索树)来维护数组元素,以便在更新后快速调整计算过程。
难度加深题目2:多维数组的最接近三数之和
给定一个多维数组(如二维数组,每个元素又是一个数组),要求在这些数组中找出所有满足三数之和最接近 target 的组合。这需要考虑如何遍历多维数组,并在不同维度上应用类似的算法思想,同时处理好组合的唯一性和接近程度的计算。
七、应用场合
- 数值逼近问题:在科学计算、数据分析等领域,经常需要从一组数据中找出某些数值的组合,使其和尽可能接近某个目标值。例如,在物理实验数据处理中,寻找最接近理论值的测量数据组合。
- 资源分配优化:在资源分配场景中,若有多种资源可供选择,每种资源有不同的数量或价值,目标是选择三种资源,使其总和最接近某个需求值,以实现资源的最优利用。
- 算法竞赛与面试:此类问题作为经典的算法题目,常用于算法竞赛和面试中,考察应聘者对数组操作、排序算法、双指针法以及数值比较等技术的掌握和应用能力。


4867

被折叠的 条评论
为什么被折叠?



