2021-12-11每日一題
阿新 • • 發佈:2021-12-11
911. 線上選舉
給你兩個整數陣列persons
和times
。在選舉中,第i
張票是在時刻為times[i]
時投給候選人persons[i]
的。
對於發生在時刻t
的每個查詢,需要找出在t
時刻在選舉中領先的候選人的編號。
在t
時刻投出的選票也將被計入我們的查詢之中。在平局的情況下,最近獲得投票的候選人將會獲勝。
實現TopVotedCandidate
類:
TopVotedCandidate(int[] persons, int[] times)
使用persons
和times
陣列初始化物件。int q(int 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] 解釋: TopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]); topVotedCandidate.q(3); // 返回 0 ,在時刻 3 ,票數分佈為 [0] ,編號為 0 的候選人領先。 topVotedCandidate.q(12); // 返回 1 ,在時刻 12 ,票數分佈為 [0,1,1] ,編號為 1 的候選人領先。 topVotedCandidate.q(25); // 返回 1 ,在時刻 25 ,票數分佈為 [0,1,1,0,0,1] ,編號為 1 的候選人領先。(在平局的情況下,1 是最近獲得投票的候選人)。 topVotedCandidate.q(15); // 返回 0 topVotedCandidate.q(24); // 返回 0 topVotedCandidate.q(8); // 返回 1
提示:
1 <= persons.length <= 5000
times.length == persons.length
0 <= persons[i] < persons.length
0 <= times[i] <= 109
times
是一個嚴格遞增的有序陣列times[0] <= t <= 109
- 每個測試用例最多呼叫
104
次q
1 import java.util.HashMap; 2 3 public class TopVotedCandidate { 4 int n=0; 5 int[] ans,time; 6public TopVotedCandidate(int[] persons, int[] times) { 7 ans=new int[times.length]; 8 n= times.length; 9 time=times; 10 //ans記錄每個時間點票數最多的人 11 int indicate=-1,MAX=-1; 12 HashMap<Integer, Integer> map = new HashMap<>(); 13 //記錄每個人的票數,維護每個時間段票數最多者 14 for (int i = 0; i < persons.length; i++) { 15 map.put(persons[i],map.getOrDefault(persons[i],0)+1); 16 if (indicate==-1){ 17 indicate=persons[i]; 18 MAX=map.get(persons[i]); 19 }else if (map.get(persons[i])>=MAX){ 20 MAX=map.get(persons[i]); 21 indicate=persons[i]; 22 } 23 //選出最多者的號碼,並存入ans陣列中 24 ans[i]=indicate; 25 } 26 } 27 28 public int q(int t) { 29 //二分查詢t時間最近的時間點 30 int l=0,r=n-1; 31 while (l<=r){ 32 int mid=(l+r)/2; 33 if (time[mid]>t){ 34 r=mid-1; 35 }else if(time[mid]<t){ 36 l=mid+1; 37 }else{ 38 return ans[mid]; 39 } 40 } 41 return ans[r]; 42 } 43 44 public static void main(String[] args) { 45 int[] p={0, 1, 0, 1, 1}; 46 int[] t={24,29,31,76,81}; 47 int[] test={28,24,29,77,30,25,76,75,81,80}; 48 TopVotedCandidate topVotedCandidate = new TopVotedCandidate(p, t); 49 for (int j : test) { 50 System.out.println(topVotedCandidate.q(j)); 51 } 52 } 53 }
需要注意的是二分法尋找左邊界的處理、
while (l<=r)對應l==r 的情況,所以返回ans[r]和ans[l]都是一樣的
l<=r對應的r為n-1,如果r=n,則應為l<r
同時也對應mid是否應該加減1