TikTok 面试题:3Sum Closest – VO 辅助 – 一亩三分地 – 代面试

Given an integer array nums of length n 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.

给定一个整数数组 nums 和一个整数 target,从数组中选出三个数,使它们的和最接近 target,返回这个三数之和。

例如:

nums = [-1, 2, 1, -4]
target = 1

最接近 target 的三数之和是:

-1 + 2 + 1 = 2

所以返回:

2

解题思路

常见做法是先排序,再使用双指针。

排序后,固定一个数 nums[i],然后用 leftright 指针寻找另外两个数。

每次计算:

sum = nums[i] + nums[left] + nums[right]

如果 sum 比当前答案更接近 target,就更新答案。

如果 sum < target,说明当前和偏小,移动 left

如果 sum > target,说明当前和偏大,移动 right

如果 sum == target,可以直接返回,因为已经是最优结果。

复杂度

时间复杂度:

O(n²)

空间复杂度:

O(1)

CSOAHelp 收录了多道 TikTok 高频面试题,包括算法题、系统设计题和真实面试流程整理。

如果你正在准备 TikTok 面试,可以通过类似题目提前熟悉面试考点和解题表达方式。

我们也有代面试,面试辅助,OA代写等服务助您早日上岸~

Leave a Reply

Your email address will not be published. Required fields are marked *