911. 線上選舉

WrRan發表於2024-09-10
題目連結 911. 線上選舉
思路 二分
題解連結 [Python/Java/JavaScript/Go] 二分查詢
關鍵點 理解題意:預處理 - 按照times得出每個離散時刻下獲勝者的person;詢問 - 二分查詢到>t的前一個時刻獲勝者
時間複雜度 \(O(n)\)
空間複雜度 \(O(n)\)

程式碼實現:

class TopVotedCandidate:

    def __init__(self, persons: List[int], times: List[int]):
        n = len(times)
        self.times = times
        self.answer = [-1] * n

        cnts = defaultdict(int)
        winner = None
        for i, person in enumerate(persons):
            cnts[person] += 1
            if winner is None or cnts[person] >= cnts[winner]:
                winner = person
            self.answer[i] = winner
        self.n = n
            
    def q(self, t: int) -> int:
        left, right = -1, self.n
        while left + 1 < right:
            mid = (left+right) // 2
            if self.times[mid] <= t:
                left = mid
            else:
                right = mid
        return self.answer[right - 1]
Python-標準庫
class TopVotedCandidate:

    def __init__(self, persons: List[int], times: List[int]):
        n = len(times)
        self.times = times
        self.answer = [-1] * n

        cnts = defaultdict(int)
        winner = None
        for i, person in enumerate(persons):
            cnts[person] += 1
            if winner is None or cnts[person] >= cnts[winner]:
                winner = person
            self.answer[i] = winner
            
    def q(self, t: int) -> int:
        return self.answer[
            bisect_right(self.times, t) - 1
        ]

相關文章