频道栏目
首页 > 资讯 > 其他 > 正文

Leetcode33. Search in Rotated Sorted Array

17-06-21        来源:[db:作者]  
收藏   我要投稿

Description

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.

cpp

class Solution {
public:
    int search(vector& nums, int target) {
        int l = 0, h = nums.size() - 1, m;
        while(l <= h){
            m = l + (h - l) / 2;
            if(target == nums[m]) return m;
            if(nums[m] <= nums[h]){
                if(target < nums[m]) h = m - 1;
                else if(target <=nums[h]) l = m + 1;
                else h = m - 1;
            }else{
                if(target > nums[m]) l = m + 1;
                else if(target >= nums[l]) h = m - 1;
                else l = m + 1;
            }
        }
        return -1;
    }
};
相关TAG标签
上一篇:Codeforces Gym 101234H Split Game
下一篇:刘强东在农村开50万家店:彻底消除对农村的价格歧视
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站