Problem
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].
class TopVotedCandidate { Maphistory = new HashMap<>(); int[] times; public TopVotedCandidate(int[] persons, int[] times) { this.times = times; Map votes = new HashMap<>(); int n = persons.length; int leader = persons[0]; for (int i = 0; i < n; i++) { votes.put(persons[i], votes.getOrDefault(persons[i], 0)+1); if (votes.get(persons[i]) >= votes.get(leader)) leader = persons[i]; history.put(times[i], leader); } } public int q(int t) { int i = Arrays.binarySearch(times, t); if (i < 0) return history.get(times[-i-2]); return history.get(times[i]); } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/72570.html
摘要:题目汉明距离是两个字符串对应位置的不同字符的个数,这里指二进制的不同位置例子我的解法先将,进行异位或运算再转化成二进制然后把去掉算出长度其他方法先算出不同位数,然后用右移运算符算出能右移几次来获取距离 1题目 The Hamming distance between two integers is the number of positions at which the corresp...
LeetCode version Problem Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, t...
摘要:题目自己的解决方法其他解决方法 1.题目International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: a maps to .-, b maps to -..., c maps to -.-., and...
摘要:题目例子我的解法其他解法求最大值然后求二分法查找 1 题目 Lets call an array A a mountain if the following properties hold: A.length >= 3There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[...
摘要:题目例子我的解法其他解法这个方法不用转化成字符串,直接得到的数再除 1. 题目 A self-dividing number is a number that is divisible by every digit it contains. For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 ...
阅读 2923·2023-04-26 01:52
阅读 3450·2021-09-04 16:40
阅读 3616·2021-08-31 09:41
阅读 1707·2021-08-09 13:41
阅读 471·2019-08-30 15:54
阅读 2910·2019-08-30 11:22
阅读 1585·2019-08-30 10:52
阅读 932·2019-08-29 13:24