- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 35 lines of Java from the credited upstream file 1157.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 2 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class MajorityChecker {2 public MajorityChecker(int[] arr) {3 this.arr = arr;4 for (int i = 0; i < arr.length; ++i) {5 if (!numToIndices.containsKey(arr[i]))6 numToIndices.put(arr[i], new ArrayList<>());7 numToIndices.get(arr[i]).add(i);8 }9 }10 11 public int query(int left, int right, int threshold) {12 for (int i = 0; i < TIMES; ++i) {13 final int randIndex = rand.nextInt(right - left + 1) + left;14 final int num = arr[randIndex];15 List<Integer> indices = numToIndices.get(num);16 final int l = firstGreaterEqual(indices, left);17 final int r = firstGreaterEqual(indices, right + 1);18 if (r - l >= threshold)19 return num;20 }21 22 return -1;23 }24 25 private static final int TIMES = 20; 26 private int[] arr;27 private Map<Integer, List<Integer>> numToIndices = new HashMap<>();28 private Random rand = new Random();29 30 private int firstGreaterEqual(List<Integer> A, int target) {31 final int i = Collections.binarySearch(A, target);32 return i < 0 ? -i - 1 : i;33 }34}35