题目
在数组中找到一个局部最小的位置
java代码
package com.lizhouwei.chapter8;
/**
* @Description: 在数组中找到一个局部最小的位置
* @Author: lizhouwei
* @CreateDate: 2018/5/8 21:43
* @Modify by:
* @ModifyDate:
*/
public class Chapter8_18 {
public int getLessIndex(int[] arr) {
if (arr.length == 1 || arr[0] < arr[1]) {
return 0;
}
int len = arr.length;
if (arr[len - 2] > arr[len - 1]) {
return len - 1;
}
int left = 1;
int right = len - 2;
int mid = 0;
while (left < right) {
mid = (left + right) / 2;
if (arr[mid] > arr[mid - 1]) {
right = mid - 1;
} else if (arr[mid] > arr[mid + 1]) {
left = mid + 1;
} else {
return mid;
}
}
return left;
}
//测试
public static void main(String[] args) {
Chapter8_18 chapter = new Chapter8_18();
int[] arr = {9, 8, 7, 1, 2, 3, 4, 5, 6};
System.out.print("数组 arr = {9, 8, 7, 1, 2, 3, 4, 5, 6}局部最小的位置为:");
int res = chapter.getLessIndex(arr);
System.out.print(res);
}
}
结果