在選舉中,第 i 張票是在時間為 times[i] 時投給 persons[i] 的。
現在,我們想要實現下面的查詢函數: TopVotedCandidate.q(int t) 將返回在 t 時刻主導選舉的候選人的編號。
在 t 時刻投出的選票也將被計入我們的查詢之中。在平局的情況下,最近獲得投票的候選人將會獲勝。
示例:
輸入:[“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]]
輸出:[null,0,1,1,0,0,1]
解釋:
時間為 3,票數分布情況是 [0],編號為 0 的候選人領先。
時間為 12,票數分布情況是 [0,1,1],編號為 1 的候選人領先。
時間為 25,票數分布情況是 [0,1,1,0,0,1],編號為 1 的候選人領先(因為最近的投票結果是平局)。
在時間 15、24 和 8 處繼續執行 3 個查詢。
代碼
class TopVotedCandidate {int[] helper,time;int n;public TopVotedCandidate(int[] persons, int[] times) {int max=0,maxP=-1;n=times.length;Map<Integer,Integer> map=new HashMap<>();helper=new int[n];time=times;for (int i=0;i<n;i++)//計算每個時間節點的贏家{map.put(persons[i],map.getOrDefault(persons[i],0)+1);if(map.get(persons[i])>=max)//更換贏家{max=map.get(persons[i]);maxP=persons[i];}helper[i]=maxP;}}public int q(int t) {int l=0,r=n-1;while (l<=r)//二分查找目標時間節點{int mid=(r-l)/2+l;if(time[mid]==t)return helper[mid] ;else if(time[mid]<t)l=mid+1;else r=mid-1;}return helper[l-1];}}/*** Your TopVotedCandidate object will be instantiated and called as such:* TopVotedCandidate obj = new TopVotedCandidate(persons, times);* int param_1 = obj.q(t);*/