Implementing the class MajorityChecker, which has the following API:
MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(…) returns the element in arr[left], arr[left+1], …, arr[right] that occurs at least threshold times, or -1 if no such element exists.
Example:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
Constraints:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000
三国杀理论:
class MajorityChecker {
int[] nums;
public MajorityChecker(int[] arr) {
nums = arr;
}
public int query(int left, int right, int threshold) {
int count = 0;
int num = 0;
for (int i = left; i <= right; i++) {
if (nums[i] == num) count++;
else {
if (count == 0) num = nums[i];
else count--;
}
}
count = 0;
for (int i = left; i <= right; i++) {
if (nums[i] == num) count++;
}
return count >= threshold ? num : -1;
}
}
/**
* Your MajorityChecker object will be instantiated and called as such:
* MajorityChecker obj = new MajorityChecker(arr);
* int param_1 = obj.query(left,right,threshold);
*/
概率角度:1/2的概率抽不中,那么抽20次还抽不中的概率是1/1000000,因此我们认为接近于0.
class MajorityChecker {
HashMap<Integer, List<Integer>> map = new HashMap<>();
Random random;
int[] arr;
public MajorityChecker(int[] arr) {
this.arr = arr;
for (int i = 0; i < arr.length; i++) {
if (!map.containsKey(arr[i])) map.put(arr[i], new ArrayList<>());
map.get(arr[i]).add(i);
}
random = new Random();
}
public int query(int left, int right, int threshold) {
int range = right - left + 1;
for (int i = 0; i < 20; i++) {
int r = random.nextInt(range);
int num = arr[left + r];
List<Integer> list = map.get(num);
int index1 = Collections.binarySearch(list, left);
int index2 = Collections.binarySearch(list, right);
if (index1 < 0) index1 = -index1-1;
if (index2 < 0) index2 = -index2-2;
if (index2 - index1 + 1 >= threshold) return num;
}
return -1;
}
}