查找这块主要是二分查找及其变形模式,需要注意的的点就是边界情况。

二分查找模板

  1. class Solution {
  2. public boolean find(int[] numbers, int target) {
  3. int left = 0;
  4. int right = numbers.length-1;
  5. while (left <right) {
  6. int mid = left + (right - left) /2;
  7. if (numbers[mid] > target) {
  8. left = mid+1;
  9. } else if (numbers[mid] < numbers[right]) {
  10. right = mid-1;
  11. } else {
  12. return true;
  13. }
  14. }
  15. return false;
  16. }
  17. }

实例题目
LeetCode 旋转数组最小值

  1. class Solution {
  2. public int minArray(int[] numbers) {
  3. int min = Integer.MAX_VALUE;
  4. int left = 0;
  5. int right = numbers.length-1;
  6. while (left <right) {
  7. int mid = left + (right - left) /2;
  8. if (numbers[mid] > numbers[right]) {
  9. left = mid+1;
  10. } else if (numbers[mid] < numbers[right]) {
  11. //注意这里是设置为mid而不是mid-1
  12. right = mid;
  13. } else {
  14. right--;
  15. }
  16. }
  17. return numbers[left];
  18. }
  19. }