题目

81. 搜索旋转排序数组 II

题解


代码

public class code81 {

    // public static boolean search(int[] nums, int target) {
    // for (int i = 0; i < nums.length; i++) {
    // if (nums[i] == target) {
    // return true;
    // }
    // }
    // return false;
    // }

    public static boolean search(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return true;
            }
            if (nums[left] == nums[mid] && nums[mid] == nums[right]) {
                left++;
                right--;
            } else if (nums[left] <= nums[mid]) {
                if (nums[left] <= target && target < nums[mid]) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } else if (nums[mid] <= nums[right]) {
                if (nums[mid] < target && target <= nums[right]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int nums[] = { 2, 5, 6, 0, 0, 1, 2 };
        int target1 = 0;
        int target2 = 3;
        boolean flag1 = search(nums, target1);
        boolean flag2 = search(nums, target2);
        System.out.println(flag1);
        System.out.println(flag2);
    }
}

参考

  1. 搜索旋转排序数组 II——题解一
  2. 二分查找(Python 代码、Java 代码)
  3. 搜索旋转排序数组 II——题解二