一、局部极小值
给定一个无序数组,没有重复元素。如果下标i的元素比左右两个元素都小,那么该下标元素是局部极小值,返回该下标。当i为0的时候不需要和左边比较,当i为数组长度-1的时候不需要和右边比较。比如2 5 3 4 7 1,那么局部极小值元素是2 3 1,返回其中任意一个元素下标即可,比如返回0就可以。要求最坏情况下是O(lgn)。
对无序数组使用二分法,当取得中点m后,比较其相邻的两个元素,如果满足则返回m。否则相当于子问题,继续二分。
public class FindPartMin {
public int find(int[] array) {
// 使用二分法
if (array == null || array.length == 0) {
return -1;
}
int i = 0, j = array.length - 1;
while (j - i > 1) {
int m = (i + j) >>> 1;
if (array[m] < array[m + 1] && array[m] < array[m - 1]) {
// find
return m;
} else if (array[m] < array[m + 1]) {
// left is like global
j = m - 1;
} else {
// right is like global
i = m + 1;
}
}
// there j - i == 1 or j == i
if (i == j) {
return i;
} else {
if (array[j] > array[i]) {
return i;
} else {
return j;
}
}
}
public static void main(String[] args) {
FindPartMin findPartMin = new FindPartMin();
int[] array = {2, 5, 3, 4, 7, 1};
System.out.println(findPartMin.find(array));
}
}