|
| 1 | +class Solution { |
| 2 | + public int findSpecialInteger(int[] arr) { |
| 3 | + int n = arr.length; |
| 4 | + int oneFourthNum = arr[n / 4]; |
| 5 | + int halfNum = arr[n / 2]; |
| 6 | + int threeFourthNum = arr[3 * n / 4]; |
| 7 | + if(Math.max(n/4, binarySearchRight(arr, 0, n - 1, oneFourthNum)) - |
| 8 | + Math.min(n/4, binarySearchLeft(arr, 0, n - 1, oneFourthNum)) >= arr.length / 4) { |
| 9 | + return oneFourthNum; |
| 10 | + } |
| 11 | + if(Math.max(n/2, binarySearchRight(arr, 0, n - 1, halfNum)) - |
| 12 | + Math.min(n/2, binarySearchLeft(arr, 0, n - 1, halfNum)) >= arr.length / 4) { |
| 13 | + return halfNum; |
| 14 | + } |
| 15 | + if(Math.max((3 * n)/4, binarySearchRight(arr, 0, n - 1, threeFourthNum)) - |
| 16 | + Math.min((3 * n)/4, binarySearchLeft(arr, 0, n - 1, threeFourthNum)) >= arr.length / 4) { |
| 17 | + return threeFourthNum; |
| 18 | + } |
| 19 | + return -1; |
| 20 | + } |
| 21 | + |
| 22 | + private int binarySearchLeft(int[] arr, int start, int end, int num) { |
| 23 | + int minIdx = Integer.MAX_VALUE; |
| 24 | + while (start < end) { |
| 25 | + int mid = (start + end) / 2; |
| 26 | + if (arr[mid] == num) { |
| 27 | + minIdx = Math.min(mid, minIdx); |
| 28 | + end = mid - 1; |
| 29 | + } |
| 30 | + else if (arr[mid] < num) { |
| 31 | + start = mid + 1; |
| 32 | + } |
| 33 | + else { |
| 34 | + end = mid - 1; |
| 35 | + } |
| 36 | + } |
| 37 | + return minIdx; |
| 38 | + } |
| 39 | + |
| 40 | + private int binarySearchRight(int[] arr, int start, int end, int num) { |
| 41 | + int maxIdx = Integer.MIN_VALUE; |
| 42 | + while (start < end) { |
| 43 | + int mid = (start + end) / 2; |
| 44 | + if (arr[mid] == num) { |
| 45 | + maxIdx = Math.max(mid, maxIdx); |
| 46 | + start = mid + 1; |
| 47 | + } |
| 48 | + else if (arr[mid] < num) { |
| 49 | + start = mid + 1; |
| 50 | + } |
| 51 | + else { |
| 52 | + end = mid - 1; |
| 53 | + } |
| 54 | + } |
| 55 | + return maxIdx; |
| 56 | + } |
| 57 | +} |
0 commit comments