# 一维数组的局部最大值查找

	public int peekFind1(int[] array) {
int len = array.length;
//len == 0 exception
int l = 0, r = len - 1;
while(r > l) {
int m = l + (r - l)/2;
if( (m - 1 < 0 || array[m] >= array[m-1]) && (m + 1 >= len || array[m] >= array[m+1]) ) {
return array[m];
}
else if( (m - 1 >= 0 && array[m-1] > array[m]) ) {
r = m-1;
}
else {
l = m+1;
}
}
return array[r];
}


# 二维数组的局部最大值查找

	public int maxNum(int[] array) {
int result = array[0];
int idx = 0;
for(int i = 1;i < array.length;i++) {
if(array[i] > result) {
result = array[i];
idx = i;
}
}
return idx;
}
public int peekFind2(int[][] matrix) {
int row = matrix.length;
//row == 0 exception
int column = matrix[0].length;
if(row == 1) return peekFind1(matrix[0]);
if(column == 1) {
int[] array = new int[row];
for(int i = 0;i < row;i++) array[i] = matrix[i][0];
return peekFind1(array);
}
int startR = 0, endR = row - 1;
while(endR > startR) {
int midR = startR + (endR - startR)/2;
int maxIdx = maxNum(matrix[midR]);
if( (midR - 1 < 0 || matrix[midR][maxIdx] >= matrix[midR - 1][maxIdx]) && (midR + 1 >= row || matrix[midR][maxIdx] >= matrix[midR + 1][maxIdx]) ) {
return matrix[midR][maxIdx];
}
else if( (midR - 1 >= 0 && matrix[midR - 1][maxIdx] > matrix[midR][maxIdx]) ) {
endR = midR - 1;
}
else {
startR = midR + 1;
}
}
return matrix[startR][maxNum(matrix[startR])];
}


posted @ 2017-05-29 21:10  weixliu  阅读(639)  评论(0编辑  收藏  举报