Leetcode C++《热题 Hot 100-31》33.搜索旋转排序数组

Leetcode C++《热题 Hot 100-31》33.搜索旋转排序数组

  1. 题目
    假设按照升序排序的数组在预先未知的某个点上进行了旋转。

( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。

搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。

你可以假设数组中不存在重复的元素。

你的算法时间复杂度必须是 O(log n) 级别。

示例 1:

输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
示例 2:

输入: nums = [4,5,6,7,0,1,2], target = 3
输出: -1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  1. 思路
  • 最早校园面试的时候见过这个题hh,然后我做这个题目的时候难住了,和我想象的不太一样,当时面试的时候求的是拐点,而这里是找值
  • 那我找拐点logn, 找到的是最小值 ,【x1, x2】递增, 【拐点x3,x4】递增
  • 根据拐点找数logn
  1. 代码
class Solution {
public:
    int search(vector<int>& nums, int target) {
        int x3  = findTurnPoint(nums);
        //cout << x3 << endl;
        int res = findKey(nums, 0, x3-1, target);
        //cout << "one " << res << endl;
        if (res != -1)
            return res;
        res = findKey(nums, x3, nums.size()-1, target);
        //cout << "two " << res << endl;
        if (res != -1)
            return res;
        return -1;

    }

    int findTurnPoint(vector<int> nums) {
        int l = 0; 
        int r = nums.size()-1;
        int mid;
        //假设数组中不存在重复元素
        while(l < r) {
            mid = (l+r) >> 1;
            if (nums[mid] >= nums[0]) {  //bug2:等于nums[0]证明index = 0,拐点在后面
                l = mid + 1;
            } else {
                r = mid;   //bug3:r不能写成mid+1,因为mid也可能是拐点
            }
        }
        return l;
    }

    int findKey(vector<int> nums, int left, int right, int key) {
        if (left > right)
            return -1;
        int l = left; 
        int r = right;
        int mid;
        //假设数组中不存在重复元素
        while(l < r) {
            mid = (l+r) >> 1;
            if (nums[mid] > key) {
                r = mid - 1;
            } else if (nums[mid] == key) {   //bug1:你要跳过mid,你必须保证mid的位置不是key才行
                return mid;
            } else {
                l = mid + 1;
            }
        }
        if (key == nums[l])
            return l;
        else
            return -1; 
    }
};
发布了205 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Alexia23/article/details/104184099
今日推荐