leetcode33 - Search in Rotated Sorted Array - medium

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
 
参考的sheep老师的模板,非常非常清晰。
首先讲一下模板,m = l + r + 1 >> 1, 因为/2这个过程取的是floor,我们手动加上1能使得m不会等于此刻的l,等下重要性就体现出来了。划分左半边和右半边的时候,m如果在左边,返回true,也就是说m可能是最后的结果,l=m,刚刚那个细节就在这里规避掉了dead loop。相反m在右边的话,返回false,m不可能是最后的结果,r=m-1. 剩下要做的就是设计好划分条件,使得true/false成立。
rotated之后,数组差不多长下面这样,考虑两种情况:target在右下这块或者target在左上这块, 找让m落在绿色区间的条件,就是返回true的
在右下:
1. m落在纵轴左边:nums[m] > nums[r]
2. m落在纵轴右边:nums[m] <= target
leetcode33 - Search in Rotated Sorted Array - medium_第1张图片
在左上:
nums[l] <= nums[m] <= target
leetcode33 - Search in Rotated Sorted Array - medium_第2张图片
 
最后记得检查l指向的是否是target
 
实现:
class Solution {
public:
    int search(vector<int>& nums, int target) {
        
        if (nums.empty())
            return -1;
        
        int l = 0, r = nums.size() - 1;
        while (l < r) {
            int m = l + r + 1 >> 1;
            if (nums[m] == target)
                return m;
            
            if (target <= nums[r]) {
                if (nums[m] <= target || nums[m] > nums[r])
                    l = m;
                else
                    r = m - 1;
            } else {
                if (nums[m] <= target && nums[m] >= nums[l])
                    l = m;
                else
                    r = m - 1;
            }
        }
        
        return nums[l] == target ? l : -1;
        
    }
};

 

你可能感兴趣的:(leetcode33 - Search in Rotated Sorted Array - medium)