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

33. Search in Rotated Sorted Arr

作者: 蜜糖_7474 | 来源:发表于2019-05-15 13:27 被阅读0次

    Suppose an array sorted in ascending order 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.

    Your algorithm's runtime complexity must be in the order of O(log n).

    Example 1:

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

    Example 2:

    Input: nums = [4,5,6,7,0,1,2], target = 3
    Output: -1

    AC代码

    class Solution {
    public:
        int search(vector<int>& nums, int target) {
            if (nums.empty()) return -1;
            int ans = -1, left = 0, right = nums.size() - 1, mid;
            while (left <= right) {
                mid = (left + right) / 2;
                if (nums[mid] == target)
                    return mid;
                else if (nums[mid] >= nums[left]) {  // mid左边有序
                    if (target >= nums[left] && target < nums[mid])
                        right = mid - 1;
                    else if (target >= nums[left] && target > nums[mid])
                        left = mid + 1;
                    else //target不在左半边
                        left = mid + 1;
                }
                else if (nums[mid] <= nums[right]) {  // mid右边有序
                    if (target >= nums[mid] && target <= nums[right])
                        left = mid + 1;
                    else //要么target不在右半边,要么在右半边同时target<nums[mid]
                        right = mid - 1;
                }
            }
            return ans;
        }
    };
    

    AC代码(稍稍精简)

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

    总结

    1、两分钟O(n),两小时O(logn),边界问题折磨的要死,后来发现不需要单独考虑1个元素与2个元素的情况
    2、二分法过于不熟悉,边界值全靠试错,需多加练习

    相关文章

      网友评论

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

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