【Leetcode】Search in Rotated Sorted Array II

题目链接:https://leetcode.com/problems/search-in-rotated-sorted-array-ii/

题目:
Follow up for “Search in Rotated Sorted Array”:
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.

思路:
找到逆序的位置,然后根据该位置将数组分为两半,分别二分查找

算法:

    public boolean search(int[] nums, int target) {
        int index = 0; // 找到旋转点即逆序的点
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] > nums[i + 1]) {
                index = i;
            }
        }
        boolean left_res = search(nums, target, 0, index);
        boolean right_res = search(nums, target, index + 1, nums.length - 1);
        return left_res || right_res;
    }

    public boolean search(int nums[], int target, int start, int end) {
        int left = start, right = end, mid = 0;
        while (left <= right) {
            mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return true;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return false;
    }

你可能感兴趣的:(LeetCode)