查找这块主要是二分查找及其变形模式,需要注意的的点就是边界情况。
二分查找模板
class Solution {
public boolean find(int[] numbers, int target) {
int left = 0;
int right = numbers.length-1;
while (left <right) {
int mid = left + (right - left) /2;
if (numbers[mid] > target) {
left = mid+1;
} else if (numbers[mid] < numbers[right]) {
right = mid-1;
} else {
return true;
}
}
return false;
}
}
实例题目
LeetCode 旋转数组最小值
class Solution {
public int minArray(int[] numbers) {
int min = Integer.MAX_VALUE;
int left = 0;
int right = numbers.length-1;
while (left <right) {
int mid = left + (right - left) /2;
if (numbers[mid] > numbers[right]) {
left = mid+1;
} else if (numbers[mid] < numbers[right]) {
//注意这里是设置为mid而不是mid-1
right = mid;
} else {
right--;
}
}
return numbers[left];
}
}