Re: [閒聊] 每日leetcode
看板Marginalman作者JerryChungYC (JerryChung)時間1年前 (2024/08/05 09:54)推噓1(1推 0噓 2→)留言3則, 2人參與討論串639/1548 (看更多)
※ 引述《sustainer123 (caster )》之銘言:
: 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.
思路:最簡單就用一個list找出count為1的值 再根據長度回傳值
Python Code:
class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
res = [_ for _ in arr if arr.count(_) == 1]
return res[k-1] if len(res) >= k else ''
272 ms / 16.72 MB
但這樣分數很醜 所以就換了個方式
用一個變數紀錄當前僅出現1次的值 如果到k就回傳 全跑完就回傳空字串
因為是要第k個 所以counter從1開始
Python Code:
class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
counter = 1
for _ in arr:
if arr.count(_) == 1:
if counter == k:
return _
else:
counter += 1
return ''
210 ms / 16.73 MB
不過這樣重複的值會再跑一次count 所以再多一個list去記錄已查過的值
Python Code:
class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
counter = 1
checked = []
for _ in arr:
if _ in checked:
continue
if arr.count(_) == 1:
if counter == k:
return _
else:
counter += 1
checked.append(_)
return ''
164 ms / 16.71 MB
想不到其他更好的了 繼續當easy守門員
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.251.52.67 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1722822896.A.838.html
推
08/05 09:59,
1年前
, 1F
08/05 09:59, 1F
→
08/05 09:59,
1年前
, 2F
08/05 09:59, 2F
→
08/05 10:00,
1年前
, 3F
08/05 10:00, 3F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 639 之 1548 篇):