LeetCode題解(1450):在既定時間做作業的學生人數(Python)

題目:原題鏈接(簡單)

解法 時間複雜度 空間複雜度 執行用時
Ans 1 (Python) O(S+E+Q)O(S+E+Q) : S爲startTime的長度,E爲endTime的長度,Q爲querytime O(S+E)O(S+E) 48ms (20.08%)
Ans 2 (Python) O(S+E)O(S+E): S爲startTime的長度,E爲endTime的長度 O(1)O(1) 40ms (72.16%)
Ans 3 (Python)

LeetCode的Python執行用時隨緣,只要時間複雜度沒有明顯差異,執行用時一般都在同一個量級,僅作參考意義。

解法一(哈希表):

def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
    start_count = collections.Counter(startTime)
    end_count = collections.Counter(endTime)
    now = 0
    for i in range(1, queryTime + 1):
        if i in start_count:
            now += start_count[i]
        if i - 1 in end_count:
            now -= end_count[i - 1]
    return now

解法二(優化解法一):

def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
    ans = 0
    for start in startTime:
        if start <= queryTime:
            ans += 1
    for end in endTime:
        if end < queryTime:
            ans -= 1
    return ans
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章