美文网首页
81. Search in Rotated Sorted Arr

81. Search in Rotated Sorted Arr

作者: 蜜糖_7474 | 来源:发表于2019-06-07 17:10 被阅读0次

    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

    (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).

    You are given a target value to search. If found in the array return true, otherwise return false.

    Example 1:

    Input: nums = [2,5,6,0,0,1,2], target = 0
    Output: true

    Example 2:

    Input: nums = [2,5,6,0,0,1,2], target = 3
    Output: false

    Follow up:

    • This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
    • Would this affect the run-time complexity? How and why?

    AC代码

    class Solution {
    public:
        bool search(vector<int>& nums, int target) {
            if (nums.empty()) return false;
            int left = 0, right = nums.size() - 1, mid;
            while (left <= right) {
                mid = (left + right) / 2;
                if (nums[mid] == target) return true;
                if (nums[left]==nums[right]) left++; //或者right--         
                else if (nums[mid] >= nums[left]) {  // mid左边有序
                    if (target >= nums[left] && target < nums[mid]) right = mid - 1;
                    else left = mid + 1;
                }
                else if (nums[mid] <= nums[right]) {  // mid右边有序
                    if (target >= nums[mid] && target <= nums[right]) left = mid + 1;
                    else right = mid - 1;
                }
            }
            return false;
        }
    };
    

    总结

    这个题与33题唯一的不同是左右两端的值可能相同,修改方法是当这种情况发生时,执行一次left++或者right--操作

    相关文章

      网友评论

          本文标题:81. Search in Rotated Sorted Arr

          本文链接:https://www.haomeiwen.com/subject/zcnmxctx.html