LeetCode 题解工作台
找出数组中的第 K 大整数
给你一个字符串数组 nums 和一个整数 k 。 nums 中的每个字符串都表示一个不含前导零的整数。 返回 nums 中表示第 k 大整数的字符串。 注意: 重复的数字在统计时会视为不同元素考虑。例如,如果 nums 是 ["1","2","2"] ,那么 "2" 是最大的整数, "2" 是第二大…
6
题型
4
代码语言
3
相关题
当前训练重点
中等 · 数组·string
答案摘要
我们可以将 数组中的字符串按照整数从大到小排序,然后取第 个元素即可。也可以使用快速选择算法,找到第 大的整数。 时间复杂度 $O(n \times \log n)$ 或 ,其中 是 数组的长度。空间复杂度 $O(\log n)$ 或 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
给你一个字符串数组 nums 和一个整数 k 。nums 中的每个字符串都表示一个不含前导零的整数。
返回 nums 中表示第 k 大整数的字符串。
注意:重复的数字在统计时会视为不同元素考虑。例如,如果 nums 是 ["1","2","2"],那么 "2" 是最大的整数,"2" 是第二大的整数,"1" 是第三大的整数。
示例 1:
输入:nums = ["3","6","7","10"], k = 4 输出:"3" 解释: nums 中的数字按非递减顺序排列为 ["3","6","7","10"] 其中第 4 大整数是 "3"
示例 2:
输入:nums = ["2","21","12","1"], k = 3 输出:"2" 解释: nums 中的数字按非递减顺序排列为 ["1","2","12","21"] 其中第 3 大整数是 "2"
示例 3:
输入:nums = ["0","0"], k = 2 输出:"0" 解释: nums 中的数字按非递减顺序排列为 ["0","0"] 其中第 2 大整数是 "0"
提示:
1 <= k <= nums.length <= 1041 <= nums[i].length <= 100nums[i]仅由数字组成nums[i]不含任何前导零
解题思路
方法一:排序或快速选择
我们可以将 数组中的字符串按照整数从大到小排序,然后取第 个元素即可。也可以使用快速选择算法,找到第 大的整数。
时间复杂度 或 ,其中 是 数组的长度。空间复杂度 或 。
class Solution:
def kthLargestNumber(self, nums: List[str], k: int) -> str:
return nlargest(k, nums, key=lambda x: int(x))[k - 1]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for understanding of string comparison versus numerical comparison.
- question_mark
Test knowledge of heap data structures, especially in maintaining kth largest elements.
- question_mark
Evaluate efficiency considerations between sorting, heaps, and Quickselect.
常见陷阱
外企场景- error
Misunderstanding how to compare strings numerically, particularly when strings have different lengths.
- error
Overusing sorting when a more efficient heap or Quickselect approach could be applied.
- error
Confusing the ordering of integers and failing to handle duplicates correctly.
进阶变体
外企场景- arrow_right_alt
Find the kth smallest integer in the array instead of the kth largest.
- arrow_right_alt
Handle an array of numbers with leading zeros.
- arrow_right_alt
Consider a scenario where k equals the length of the array.