问题描述

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.

Your algorithm's runtime complexity must be in the order of O(log n).

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

参考答案

class Solution {
public:
int search(vector<int>& nums, int target) {
if(nums.size() == ) return -;
int l = ;
int r = nums.size()-;
while(l<r){
int mid = (l+r)>>;
if(nums[l]<=nums[mid]){
if(target<=nums[mid] && target >= nums[l]) r = mid;
else l = mid +;
}else if(nums[mid]<nums[r]){
if(target>nums[mid] && target <= nums[r]) l = mid +;
else r = mid;
}
}
if(target == nums[l]) return r;
return -;
}
};

答案描述

由于不知道序列是否有序,因此在进行二分搜索的时候,需要先确定在什么区间:

1. 低位< 中位:意味着从 低位 到 中位,一定是有序的。如果循环的连接点,没有过中位,那么中位海拔更低,低位海拔更高,这个时候,有序的数列在,

2. 中位<高位:之间,这一段里面就是有序的,因此可以在这个区间内进行搜索。

宗旨,时刻保持有序。

最新文章

  1. 推荐eclipse插件Properties Editor
  2. CI,从数据库读取数据
  3. angularjs的$filter使用
  4. 【排列组合】bzoj3505 [Cqoi2014]数三角形
  5. python流程控制语句 for循环 - 1
  6. 无奈卸载Clover 转投TotalCommand
  7. ToolStripStatusLabel设置时间自动更新
  8. 【HDOJ】1254 推箱子
  9. NYOJ 45 棋盘覆盖
  10. Cookie 的设置和获取
  11. Java去除字符串中的空格
  12. 部署Replica Sets及查看相关配置
  13. BZOJ 2806: [Ctsc2012]Cheat [广义后缀自动机 单调队列优化DP 二分]
  14. iOS rebuild from bitcode对ipa大小的影响
  15. python数据结构与算法第五天【顺序表】
  16. 在 VS 2013/2015 中禁用 nuget 包的源代码管理
  17. 初始nginx(启动运行) 使用nginx做一个简单的静态资源服务器
  18. Hybris 用户注册的时候何如添加指定的用户组
  19. install kubernetes cluster k8s集群安装
  20. 使用css3美化复选框

热门文章

  1. [bzoj 1010][HNOI 2008]玩具装箱
  2. 8. String to Integer (atoi) ---Leetcode
  3. git 和conding.net 超详细超简单安装
  4. Alpha项目冲刺! Day4-产出
  5. WebSocketSharp 创建客户端和服务端
  6. Delphi BASE64单元EncdDecd的修改
  7. GO -- 遍历删除 数组 slice
  8. yarn 单点故障 重启 ResourceManger Restart
  9. PHP获取上周一和上个月
  10. sppNet论文学习