LeetCode 题解工作台

K 和数对的最大数目

给你一个整数数组 nums 和一个整数 k 。 每一步操作中,你需要从数组中选出和为 k 的两个整数,并将它们移出数组。 返回你可以对数组执行的最大操作数。 示例 1: 输入: nums = [1,2,3,4], k = 5 输出: 2 解释: 开始时 nums = [1,2,3,4]: - 移出 …

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

我们对 进行排序。然后 , 分别指向 首尾元素,判断两整数之和 与 的大小关系。 - 若 $s = k$,说明找到了两个整数,满足和为 ,答案加一,然后 , 向中间移动;

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 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 <= 105
  • 1 <= nums[i] <= 109
  • 1 <= k <= 109
lightbulb

解题思路

方法一:排序

我们对 numsnums 进行排序。然后 ll, rr 分别指向 numsnums 首尾元素,判断两整数之和 sskk 的大小关系。

  • s=ks = k,说明找到了两个整数,满足和为 kk,答案加一,然后 ll, rr 向中间移动;
  • s>ks \gt k,则 rr 指针向左移动;
  • s<ks \lt k,则 ll 指针向右移动;
  • 继续循环判断,直至 lrl \geq r

循环结束,返回答案。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(logn)O(\log n)。其中 nnnumsnums 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

K 和数对的最大数目题解:数组·哈希·扫描 | LeetCode #1679 中等