LeetCode 题解工作台
数组中第 K 个独一无二的字符串
独一无二的字符串 指的是在一个数组中只出现过 一次 的字符串。 给你一个字符串数组 arr 和一个整数 k ,请你返回 arr 中第 k 个 独一无二的字符串 。如果 少于 k 个独一无二的字符串,那么返回 空字符串 "" 。 注意,按照字符串在原数组中的 顺序 找到第 k 个独一无二字符串。 示例…
4
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们可以用一个哈希表 记录每个字符串出现的次数,然后再遍历一次数组,对于每个字符串,如果它出现的次数为 ,那么就将 减一,直到 减为 ,返回当前字符串即可。 时间复杂度 ,空间复杂度 ,其中 为数组 所有字符串的长度之和。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
独一无二的字符串 指的是在一个数组中只出现过 一次 的字符串。
给你一个字符串数组 arr 和一个整数 k ,请你返回 arr 中第 k 个 独一无二的字符串 。如果 少于 k 个独一无二的字符串,那么返回 空字符串 "" 。
注意,按照字符串在原数组中的 顺序 找到第 k 个独一无二字符串。
示例 1:
输入:arr = ["d","b","c","b","c","a"], k = 2
输出:"a"
解释:
arr 中独一无二字符串包括 "d" 和 "a" 。
"d" 首先出现,所以它是第 1 个独一无二字符串。
"a" 第二个出现,所以它是 2 个独一无二字符串。
由于 k == 2 ,返回 "a" 。
示例 2:
输入:arr = ["aaa","aa","a"], k = 1 输出:"aaa" 解释: arr 中所有字符串都是独一无二的,所以返回第 1 个字符串 "aaa" 。
示例 3:
输入:arr = ["a","b","a"], k = 3 输出:"" 解释: 唯一一个独一无二字符串是 "b" 。由于少于 3 个独一无二字符串,我们返回空字符串 "" 。
提示:
1 <= k <= arr.length <= 10001 <= arr[i].length <= 5arr[i]只包含小写英文字母。
解题思路
方法一:哈希表 + 计数
我们可以用一个哈希表 记录每个字符串出现的次数,然后再遍历一次数组,对于每个字符串,如果它出现的次数为 ,那么就将 减一,直到 减为 ,返回当前字符串即可。
时间复杂度 ,空间复杂度 ,其中 为数组 所有字符串的长度之和。
class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
cnt = Counter(arr)
for s in arr:
if cnt[s] == 1:
k -= 1
if k == 0:
return s
return ""
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Check for familiarity with hash maps and array scanning.
- question_mark
Verify the candidate's understanding of distinct elements and efficient lookups.
- question_mark
Evaluate their approach to handling edge cases, especially with fewer distinct strings.
常见陷阱
外企场景- error
Misunderstanding what counts as a distinct string; strings must appear only once in the array.
- error
Failing to handle the case where fewer than `k` distinct strings exist, leading to incorrect results.
- error
Not efficiently using a hash map or failing to terminate the scan early when `k` distinct strings are found.
进阶变体
外企场景- arrow_right_alt
Return the first distinct string instead of the kth one.
- arrow_right_alt
Modify the function to return the kth most frequent distinct string.
- arrow_right_alt
Handle larger arrays with optimized space and time complexities, exploring advanced hashing techniques.