lc 搜索旋转排序数组

链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array/

代码:

#include <algorithm>
class Solution {
public:
    
    int search(vector<int>& nums, int target) {
        int n = nums.size();
        if(n == 0) return -1;
        if(n == 1) return (nums[0]==target) ? 0 : -1;
        int l = 0;
        int h = n-1;
        while(l <= h) {
            int mid = (l+h) >> 1;
            if(nums[mid] == target) return mid;
            if(nums[0] <= nums[mid]) {
                if(nums[0] <= target && target < nums[mid]) {
                    h = mid-1;
                }
                else {
                    l = mid+1;
                }
            }
            else {
                if(nums[mid] < target && target <= nums[n-1]) {
                    l = mid+1;
                }
                else {
                    h = mid-1;
                }
            }
        }
        return -1;
    }
};
View Code

思路:二分的本质是能够排除一半的元素所以能够加快速度,所以仔细思考能否舍弃不可能解。

posted on 2020-05-22 23:50  FriskyPuppy  阅读(218)  评论(0编辑  收藏  举报

导航