码迷,mamicode.com
首页 > 其他好文 > 详细

33. Search in Rotated Sorted Array

时间:2017-02-04 12:25:18      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:space   value   vector   oat   exists   ase   stream   class   code   

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;
    }
};





33. Search in Rotated Sorted Array

标签:space   value   vector   oat   exists   ase   stream   class   code   

原文地址:http://www.cnblogs.com/zhxshseu/p/a2412c8ec0df3ca09ffcd24487101339.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!