题目:
Local minimum of an array.Write a program that, given an arraya[] of N distinct integers, finds alocal minimum: an indexi such that a[i-1] < a[i] < a[i+1].Your program should use ~2lgN compares in the worst case
书中给出的解决思路是:
Answer: Examine the middle valuea[N/2] and its two neighbors a[N/2 - 1] and a[N/2 + 1]. Ifa[N/2] is a local minimum, stop; otherwise search in the half with the smaller neighbor
这个题目考虑了很久,也没有想明白,在stackoverflow里面看了一些回答之后,觉得这个题目给的条件是有问题的,或者说不充分的;
有几个点需要限制:
1.所有的元素不能有相同的,如果有相同的话,那么递归条件就需要进行重新处理;
思路:
array[from-to],
1、两个端点array[from] < array[from+1] ,或者aray[to] < array[to-1],是极小值;
2、如果array只有一个值,这种情况可以认为有极小值,也可以认为没有;
3、进入递归条件时,array满足下面的条件 array[from] > array[from+1],array[to] > array[to-1];
mid = (from+to)/2;
IF array[mid] > array[mid+1] THEN find in [mid, to];
IF array[mid] > array[mid-1] THEN find in [from ,mid];
IF array[mid] < array[mid+1] && array[mid-1] > array[mid] RETURN mid;
ELSE break;
根据上面的算法,java实现如下:
package com.frozenxia.algorithm.basic.exercises;
public class LocalMinimun1418 {
public static void main(String[] args) {
int arry[] = { 9, 8, 7, 3, 10 };
System.out.println(new LocalMinimun1418().findLocaMinimal(arry));
}
int findLocaMinimal(int arry[]) {
if (arry == null)
return -1;
int lenth = arry.length;
if (lenth == 0)
return -1;
if (lenth == 1)
return 0;
if (lenth == 2)
return arry[0] < arry[1] ? 0 : -1;
if (arry[0] < arry[1])
return 0;
if (arry[lenth - 1] < arry[lenth - 2])
return lenth - 1;
int left = 0;
int right = lenth - 1;
while (left < right) {
if (right - left < 2)
break;
int mid = (left + right) / 2;
System.out.println(mid);
if (arry[mid] > arry[mid - 1]) {
right = mid;
} else if (arry[mid] > arry[mid + 1]) {
left = mid;
} else if (arry[mid] < arry[mid - 1] && arry[mid] < arry[mid + 1]) {
return mid;
} else {
break;
}
}
return -1;
}
}