1.4.20双调查找。如果一个数组中的所有元素是先递增后递减的,则称这个数组为双调的。编写一个程序,给定一个含有N 个不同int 值的双调数组,判断它是否含有给定的整数。程序在最坏情况下所需的比较次数为~3lgN
思路先找出最大值,然后分割进行二分查找;
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; }