lintcode-搜索旋转排序数组-62
来源:互联网 发布:光脚马拉松知乎 编辑:程序博客网 时间:2024/05/14 03:01
假设有一个排序的按未知的旋转轴旋转的数组(比如,0 1 2 4 5 6 7 可能成为4 5 6 7 0 1 2)。给定一个目标值进行搜索,如果在数组中找到目标值返回数组中的索引位置,否则返回-1。
你可以假设数组中不存在重复的元素。
样例
给出[4, 5, 1, 2, 3]和target=1,返回 2
给出[4, 5, 1, 2, 3]和target=0,返回 -1
解题思路:旋转数组实际上是两个递增数组的组成,且第一个数组中的任意一个值都大于第二个数组的最大值,还是用二分查找的思想。
class Solution { public: int search(vector<int> &nums, int target) { if(nums.empty()) return -1; int begin=0; int end=nums.size()-1; while(begin<=end){ int mid=begin+(end-begin)/2; if(nums[mid]==target) return mid; if(nums[mid]>nums[begin]){ //此时begin和mid肯定处在同一个递增数组上 //那么就直接运用原始的二分查找 if(nums[begin]<=target&&target<nums[mid]) end=mid-1; else begin=mid+1; }else{ //此时mid处于第二个递增数组 begin处于第一个递增数组 自然的mid和end肯定处于第二个递增数组上 //还是直接运用原始的二分查找思想 if(nums[mid]<target&&target<=nums[end]) begin=mid+1; else end=mid-1; } } return -1; }};
0 0
- lintcode-搜索旋转排序数组-62
- LintCode 62 搜索旋转排序数组
- LintCode 62 搜索旋转排序数组
- LintCode-搜索旋转排序数组
- LintCode : 搜索旋转排序数组
- LintCode:搜索旋转排序数组
- LintCode:搜索旋转排序数组
- *[Lintcode]搜索旋转排序数组
- lintcode,搜索旋转排序数组
- Lintcode 搜索旋转排序数组
- lintcode--搜索旋转排序数组
- LintCode-搜索旋转排序数组 II
- LintCode : 搜索旋转排序数组 II
- lintcode-搜索旋转排序数组II-63
- LintCode:搜索旋转排序数组 II
- Lintcode 搜索旋转排序数组 II
- LintCode 63 搜索旋转排序数组 II
- LintCode:M-搜索旋转排序数组
- 31. 匿名与闭包
- SQLAlchemy中设置Column的默认值
- 异常值(outlier)的判别与剔除
- Android之AsyncTask异步任务详解总结
- 《剑指offer》左旋转字符串
- lintcode-搜索旋转排序数组-62
- linux下使用ssh-keygen生成公钥私钥对
- 文件读取的方法
- LeetCode122——Best Time to Buy and Sell Stock II
- 程序员如何做到『编程速度又快,Bug 数量又少』?
- 海量数据处理面试题
- 轻松访问多种类型数据库,database.xml文件的配置方法
- pylearn2安装及测试
- Mongodb新增的聚合方法及其Java客户端