911. Online Election leetcode
阿新 • • 發佈:2018-12-11
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 most10000
times per test case.TopVotedCandidate.q(int t)
is always called witht >= times[0]
.
題目大意:給定一個person陣列和time陣列,person[i],time[i]意味著在time[i]這個時候有人給person[i]這個人投了一票
要求對於給定的每個時間,找出這個時間得票最多的人。
一開始我寫的很複雜,記錄了每次投票後所有人的總得票,然後對於每個時間都去找小於等於給定時間的最小值。。程式碼寫的很是複雜,結束後我參考了discuss區大佬們的程式碼,豁然開朗。
class TopVotedCandidate {
public TreeMap<Integer, Integer> tm = new TreeMap<>();
public TopVotedCandidate(int[] persons, int[] times) {
int[] count = new int[persons.length];
for (int i = 0, max = -1; i < times.length; ++i) {
++count[persons[i]];
if (max <= count[persons[i]]) {
max=count[persons[i]];
tm.put(times[i], persons[i]);
}
}
}
public int q(int t) {
return tm.floorEntry(t).getValue();
}
}
遍歷每次投票,加入到TreeMap中,更新每次投票後目前獲得票數最高的人和其得票,存放於另外一個數組中。這樣還解決了如果票數一樣得找出最近投票那個人這個問題。