Re: [閒聊] 每日leetcode
看板Marginalman作者sustainer123 (caster )時間1年前 (2024/08/05 08:50)推噓0(0推 0噓 0→)留言0則, 0人參與討論串637/1548 (看更多)
https://leetcode.com/problems/kth-distinct-string-in-an-array
2053. Kth Distinct String in an Array
distinct string代表此字串在該陣列中只出現一次
給定陣列arr跟數字k 請回傳第k個distinct string
如果 distinct string < k 回傳空字串
Example 1:
Input: arr = ["d","b","c","b","c","a"], k = 2
Output: "a"
Explanation:
The only distinct strings in arr are "d" and "a".
"d" appears 1st, so it is the 1st distinct string.
"a" appears 2nd, so it is the 2nd distinct string.
Since k == 2, "a" is returned.
Example 2:
Input: arr = ["aaa","aa","a"], k = 1
Output: "aaa"
Explanation:
All strings in arr are distinct, so the 1st string "aaa" is returned.
Example 3:
Input: arr = ["a","b","a"], k = 3
Output: ""
Explanation:
The only distinct string is "b". Since there are fewer than 3 distinct
strings, we return an empty string "".
Constraints:
1 <= k <= arr.length <= 1000
1 <= arr[i].length <= 5
arr[i] consists of lowercase English letters.
思路:
哈希表記數
然後把出現次數 == 1的數字放進新陣列
最後確認長度回傳答案 end
Python Code:
class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
record = defaultdict(int)
for c in arr:
record[c] += 1
distinct = [k for k,v in record.items() if v == 1]
if k > len(distinct):
return ""
else:
return distinct[k-1]
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.194.160.111 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1722819045.A.42B.html
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 637 之 1548 篇):