Re: [閒聊] 每日leetcode

作者: JerryChungYC (JerryChung)   2024-08-05 09:54:54
※ 引述《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守門員

Links booklink

Contact Us: admin [ a t ] ucptt.com