LeetcodeSearch in Rotated Sorted Array II

Posted wuezs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetcodeSearch 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;
    }

以上是关于LeetcodeSearch in Rotated Sorted Array II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCodeSearch in Rotated Sorted Array——旋转有序数列找目标值

[Lintcode]62. Search in Rotated Sorted Array/[Leetcode]33. Search in Rotated Sorted Array

Search in Rotated Sorted Array

Search in Rotated Sorted Array

33. Search in Rotated Sorted Array *HARD*

33. Search in Rotated Sorted Array