首页 > 代码库 > 33. Search in Rotated Sorted Array

33. Search in Rotated Sorted Array

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.

分析

二分查找,
首先判断中间数是否为所求,是则返回,否则继续;
判断中间数是属于哪个序列,是左递增序列,还是右递增序列:
左递增:
    判断target是否在左递增序列中,是则更新 R = M - 1;
    否则 L = M + 1;
右递增:
    判断target是否在右递增序列中,是则更新 L = M + 1;
    否则 R = M - 1;
技术分享

技术分享
 
 
技术分享

技术分享

技术分享

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
    int search(vector<int>& nums, int target) {
        int l = 0, r = nums.size() - 1, m, result = -1;
        while(l <= r){
            m = (l + r) >> 1;
            if(nums[m] == target)
                return m;
            if(nums[l] <= nums[m])// indicate that the nums[m] is in the ascending order part
            {
                if( nums[l] <= target && nums[m] > target){// target is in [l,m)
                    r = m - 1;
                }
                else//target is in [m,R)
                    l = m + 1;
                }
            }
            else{
                if(nums[m] < target && nums[r] >= target){ //target is in (m,r]
                    l = m + 1;
                }
                else{// target is in [l,m)
                    r = m - 1;
                }
            }
        }//end of while
        return -1;
    }
};



null


33. Search in Rotated Sorted Array