LeetCode 题解工作台
K 和数对的最大数目
给你一个整数数组 nums 和一个整数 k 。 每一步操作中,你需要从数组中选出和为 k 的两个整数,并将它们移出数组。 返回你可以对数组执行的最大操作数。 示例 1: 输入: nums = [1,2,3,4], k = 5 输出: 2 解释: 开始时 nums = [1,2,3,4]: - 移出 …
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们对 进行排序。然后 , 分别指向 首尾元素,判断两整数之和 与 的大小关系。 - 若 $s = k$,说明找到了两个整数,满足和为 ,答案加一,然后 , 向中间移动;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 nums 和一个整数 k 。
每一步操作中,你需要从数组中选出和为 k 的两个整数,并将它们移出数组。
返回你可以对数组执行的最大操作数。
示例 1:
输入:nums = [1,2,3,4], k = 5 输出:2 解释:开始时 nums = [1,2,3,4]: - 移出 1 和 4 ,之后 nums = [2,3] - 移出 2 和 3 ,之后 nums = [] 不再有和为 5 的数对,因此最多执行 2 次操作。
示例 2:
输入:nums = [3,1,3,4,3], k = 6 输出:1 解释:开始时 nums = [3,1,3,4,3]: - 移出前两个 3 ,之后nums = [1,4,3] 不再有和为 6 的数对,因此最多执行 1 次操作。
提示:
1 <= nums.length <= 1051 <= nums[i] <= 1091 <= k <= 109
解题思路
方法一:排序
我们对 进行排序。然后 , 分别指向 首尾元素,判断两整数之和 与 的大小关系。
- 若 ,说明找到了两个整数,满足和为 ,答案加一,然后 , 向中间移动;
- 若 ,则 指针向左移动;
- 若 ,则 指针向右移动;
- 继续循环判断,直至 。
循环结束,返回答案。
时间复杂度 ,空间复杂度 。其中 为 的长度。
class Solution:
def maxOperations(self, nums: List[int], k: int) -> int:
nums.sort()
l, r, ans = 0, len(nums) - 1, 0
while l < r:
s = nums[l] + nums[r]
if s == k:
ans += 1
l, r = l + 1, r - 1
elif s > k:
r -= 1
else:
l += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates knowledge of hash tables for efficiently pairing elements.
- question_mark
The candidate employs greedy algorithms or two-pointer techniques to find pairs in linear time.
- question_mark
The candidate shows understanding of time-space trade-offs when deciding between hash table and sorting approaches.
常见陷阱
外企场景- error
Failing to check if elements are still available in the hash table before forming pairs can lead to overcounting.
- error
Not handling edge cases like no pairs existing or repeated elements in the array.
- error
Using inefficient approaches like brute force pair finding, which would result in O(n^2) time complexity.
进阶变体
外企场景- arrow_right_alt
Modify the problem to find k-sum pairs instead of pairs, expanding the problem to larger sums.
- arrow_right_alt
Change the problem so that you need to return the sum of the elements in the valid pairs.
- arrow_right_alt
Add constraints where the array contains duplicates, and elements can only be used once in all pairs.