1. 程式人生 > >LeetCode - Online Election

LeetCode - Online Election

In an election, the i-th vote was cast for persons[i] at time times[i].

Now, we would like to implement the following query function: TopVotedCandidate.q(int t) will return the number of the person that was leading the election at time t.  

Votes cast at time t will count towards our query.  In the 
case of a tie, the most recent vote (among tied candidates) wins. Example 1: Input: ["TopVotedCandidate","q","q","q","q","q","q"], [[[0,1,1,0,0,1,0],[0,5,10,15,20,25,30]],[3],[12],[25],[15],[24],[8]] Output: [null,0,1,1,0,0,1] Explanation: At time 3, the votes are [0], and 0 is leading. At time 12, the votes are [0,1,1], and 1 is leading. At time
25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.) This continues for 3 more queries at time 15, 24, and 8. Note: 1 <= persons.length = times.length <= 5000 0 <= persons[i] <= persons.length times is a strictly increasing array with all elements in [0, 10^9]. TopVotedCandidate.q is called at most
10000 times per test case. TopVotedCandidate.q(int t) is always called with t >= times[0].

所以這個題使用List儲存每個時間點對應的當前的獲得票數最多的person。在q(t)中,使用二分查詢到第一個小於t的times位置,然後返回這個位置對應的時間得票最多的person即可。

平均的時間複雜度是O(logn),空間複雜度是O(N).

class TopVotedCandidate {
    //persons [0,1,1,0,0,1,0]
    //times [0,5,10,15,20,25,30]
    List<int[]> list;
    
    public TopVotedCandidate(int[] persons, int[] times) {
        list = new ArrayList<>();
        Map<Integer, Integer> map = new HashMap<>();
        int lead = -1;
        int leadP = -1;
        for (int i = 0; i < persons.length; i++){
            map.put(persons[i], map.getOrDefault(persons[i],0)+1);
            int[] pair = new int[2];
            pair[0] = times[i];
            
            if(map.get(persons[i]) >= lead){
                lead = map.get(persons[i]);
                leadP=persons[i];
            }    
            pair[1] = leadP;
            list.add(pair);
        }
    }
    
    public int q(int t) {
        int l = 0;
        int r = list.size()-1;
        while(l <= r){
            int mid = l + (r-l)/2;
            if(t == list.get(mid)[0]){
                return list.get(mid)[1];
            }
            else if(t < list.get(mid)[0]){
                r = mid-1;
            }
            else{
                l = mid+1;
            }
        }
        return list.get(r)[1];
        
    }
}

/**
 * Your TopVotedCandidate object will be instantiated and called as such:
 * TopVotedCandidate obj = new TopVotedCandidate(persons, times);
 * int param_1 = obj.q(t);
 */