leetcode:search-in-rotated-sorted-array
来源:互联网 发布:sai软件官方下载 编辑:程序博客网 时间:2024/06/14 04:51
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,0 1 2 4 5 6 7might become4 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.
Answer:
class Solution {
public:
int search(int A[], int n, int target) {
//You may assume no duplicate exists in the array.
//本题变相考查二分搜索
int l=0,h=n,m;
while(l<h){ //区间为左闭右开
m = l+((h-l)>>1);
if(A[m]==target)return m;
if(A[m]>A[l]){ //说明左边有序
if(target<A[m]&&target>=A[l]){ //搜索左区间,这里用target>=A[l]而非target>A[h-1],可以在没有翻转时,逻辑也是对的
h=m;
}else{ //右区间
l=m+1;
}
}else{ //说明右边有序
if(A[m]<target&&target<=A[h-1]){ //搜索右区间
l=m+1;
}else{ //左区间
h=m;
}
}
}
return -1;
}
};
- [leetcode][search] Search in Rotated Sorted Array
- LeetCode: Search in Rotated Sorted Array
- LeetCode: Search in Rotated Sorted Array II
- LeetCode Search in Rotated Sorted Array
- LeetCode Search in Rotated Sorted Array II
- [Leetcode] Search in Rotated Sorted Array
- LeetCode : Search in Rotated Sorted Array
- LeetCode : Search in Rotated Sorted Array II
- [LeetCode] Search in Rotated Sorted Array II
- [LeetCode] Search in Rotated Sorted Array
- [Leetcode] Search in a Rotated Sorted Array
- [Leetcode] Search in Rotated Sorted Array II
- leetcode 97: Search in Rotated Sorted Array
- [LeetCode] Search in Rotated Sorted Array
- [leetcode] Search in Rotated Sorted Array
- [leetcode] Search in Rotated Sorted Array II
- Leetcode Search in Rotated Sorted Array
- [LeetCode]Search in Rotated Sorted Array
- C++ 类相关
- Kali Linux简介
- Ubuntu Apache2绑定多个域名
- JAVA面试中问及HIBERNATE与 MYBATIS的对比
- mvn 命令
- leetcode:search-in-rotated-sorted-array
- 关于消息队列的使用
- system ui powerUI
- ABAP SE37 FM 提交 commit
- Spring-@ModelAttribute
- EventBus3.0-怎么开始使用
- handler机制的原理
- 计算机启动及程序运行
- ACM学习历程12——Map映照容器