[Leetcode]Search in Rotated Sorted Array

来源:互联网 发布:township mac 绿钞 编辑:程序博客网 时间:2024/06/07 14:18

Search in Rotated Sorted Array My Submissions Question
Total Accepted: 78974 Total Submissions: 271221 Difficulty: Hard
Suppose a sorted array 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.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? Yes No
Discuss

好久没有那种一次AC的快感了。。TAT
这道又是看了题解才会做的,在此之前我还天真的以为二分查找已经没问题了,突然又觉得二分查找不简单,特别灵活多变,坑也比较多

class Solution {public:    int search(vector<int>& nums, int target) {        int len = nums.size();        if(!len)    return -1;        int l = 0;        int r = len - 1;        int mid;        while(l < r - 1){            mid = l + (r - l) / 2;            if(nums[mid] == target) return mid;            if(nums[mid] > nums[r]){//mid在数组左边                if(target < nums[mid] && target >= nums[l]){//一定是大于等于,考虑这个[3,5,1],key = 3                    r = mid - 1;                }                else{                    l = mid + 1;                }            }            else if(nums[mid] < nums[l]){//mid在数组右边                if(target > nums[mid] && target <= nums[r]){//一定是小于等于,考虑这个[5,1,3],key = 3                    l = mid + 1;                }                else{                    r = mid - 1;                }            }            else{                if(target < nums[mid]){                    r = mid - 1;                }                else{                    l = mid + 1;                }            }        }        if(nums[r] == target)   return r;        else if(nums[l] == target)  return l;        else return -1;    }};

继续努力吧!

0 0
原创粉丝点击