Leetcode:Search in Rotated Sorted Array 旋转数组查找

Search in Rotated Sorted Array I

Search in Rotated Sorted Array II

 

Suppose a sorted array is rotated at some pivot unknown to you beforehand.



(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).



You are given a target value to search. If found in the array return its index, otherwise return -1.



You may assume no duplicate exists in the array.

 

解题思路看我博文 二分查找的那些事儿 的第九题,讲解的非常详细,很好理解。

class Solution {

public:

    int search(int A[], int n, int target) {

        assert(A != NULL && n >= 0);

        int low = 0;

        int high = n - 1;

        while (low <= high) {

            int mid = low + (high - low) / 2;

            if (A[mid] == target) {

                return mid;

            } else if (A[low] <= A[mid]) {

                if (A[low] <= target && target < A[mid]) {

                    high = mid - 1;

                } else {

                    low = mid + 1;

                }

            } else if (A[low] > A[high]) {

                if (A[mid] < target && target <= A[high]) {

                    low = mid + 1;

                } else {

                    high = mid - 1;

                }

            } 

        }

        return -1;

    }

};

 

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.

 

当存在重复元素时,前面的结论就不成立了。

上题中,如果 A[low] <= A[mid] 则可以确定 [low, mid] 区间已经是递增的。

但是在此题中,此结论不成立,如 [1, 3, 1, 1, 1]  A[low] = 1, A[mid] = 1;  区间不是递增的。

此时,我们可以区分为两种情况:

当A[low] < A[mid] 此时[low, mid] 一定是递增的

当A[low] == A[mid],此时我们递增low

class Solution {

public:

    bool search(int A[], int n, int target) {

        assert(A != NULL && n >= 0);

        int low = 0;

        int high = n - 1;

        while (low <= high) {

            int mid = low + (high - low) / 2;

            if (A[mid] == target) {

                return true;

            } else if (A[low] < A[mid]) {

                if (A[low] <= target && target < A[mid]) {

                    high = mid - 1;

                } else {

                    low = mid + 1;

                }

            } else if (A[low] > A[mid]) {

                if (A[mid] < target && target <= A[high]) {

                    low = mid + 1;

                } else {

                    high = mid - 1;

                }

            } else {

                low++;

            }

        }

        return false;

    }

};

 

你可能感兴趣的:(LeetCode)