思路先找出最大值,然后分割进行二分查找;
private static int q1_4_20(int[] N, int key) { int l = 0; int r = N.length - 1; int aims = 0; //找最大值 while (l < r) { aims = l + ((r - l) >> 1); if (N[aims] > N[aims - 1] && N[aims] < N[aims + 1]) { l = aims; } else if (N[aims] < N[aims - 1] && N[aims] > N[aims + 1]) { r = aims; } else { break; } } //左边 int left = 0; int right = aims; int mid; while (left <= right) { mid = left + ((right - left) >> 1); if (N[mid] > key) { right = mid - 1; } else if (N[mid] < key) { left = mid + 1; } else { return mid; } } //右边,大小反过来排列,和上面不一样 left = aims; right = N.length - 1; while (left <= right) { mid = left + ((right - left) >> 1); if (N[mid] < key) { right = mid - 1; } else if (N[mid] > key) { left = mid + 1; } else { return mid; } } return -1; }