LC 33. Search in Rotated Sorted Array
2024-08-27 08:49:48
问题描述
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. 中位<高位:之间,这一段里面就是有序的,因此可以在这个区间内进行搜索。
宗旨,时刻保持有序。
最新文章
- 推荐eclipse插件Properties Editor
- CI,从数据库读取数据
- angularjs的$filter使用
- 【排列组合】bzoj3505 [Cqoi2014]数三角形
- python流程控制语句 for循环 - 1
- 无奈卸载Clover 转投TotalCommand
- ToolStripStatusLabel设置时间自动更新
- 【HDOJ】1254 推箱子
- NYOJ 45 棋盘覆盖
- Cookie 的设置和获取
- Java去除字符串中的空格
- 部署Replica Sets及查看相关配置
- BZOJ 2806: [Ctsc2012]Cheat [广义后缀自动机 单调队列优化DP 二分]
- iOS rebuild from bitcode对ipa大小的影响
- python数据结构与算法第五天【顺序表】
- 在 VS 2013/2015 中禁用 nuget 包的源代码管理
- 初始nginx(启动运行) 使用nginx做一个简单的静态资源服务器
- Hybris 用户注册的时候何如添加指定的用户组
- install kubernetes cluster k8s集群安装
- 使用css3美化复选框