- 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
- 42 lines of Java from the credited upstream file 1906.java.
- The implementation visibly relies on sequence storage.
- 4 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 Solution {2 public int[] minDifference(int[] nums, int[][] queries) {3 int[] ans = new int[queries.length];4 List<Integer>[] numToIndices = new List[101];5 6 for (int i = 1; i <= 100; ++i)7 numToIndices[i] = new ArrayList<>();8 9 for (int i = 0; i < nums.length; ++i)10 numToIndices[nums[i]].add(i);11 12 if (numToIndices[nums[0]].size() == nums.length) {13 Arrays.fill(ans, -1);14 return ans;15 }16 17 for (int i = 0; i < queries.length; ++i) {18 final int l = queries[i][0];19 final int r = queries[i][1];20 int prevNum = -1;21 int minDiff = 101;22 for (int num = 1; num <= 100; ++num) {23 List<Integer> indices = numToIndices[num];24 final int j = firstGreaterEqual(indices, l);25 if (j == indices.size() || indices.get(j) > r)26 continue;27 if (prevNum != -1)28 minDiff = Math.min(minDiff, num - prevNum);29 prevNum = num;30 }31 ans[i] = minDiff == 101 ? -1 : minDiff;32 }33 34 return ans;35 }36 37 private int firstGreaterEqual(List<Integer> A, int target) {38 final int i = Collections.binarySearch(A, target);39 return i < 0 ? -i - 1 : i;40 }41}42