[LeetCode]Search in Rotated Sorted Array
来源:互联网 发布:西安交大电气考研知乎 编辑:程序博客网 时间:2024/06/06 00:45
Suppose a sorted array 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.
题目翻译:在不重复的循环有序数组(如0 1 2 3 4 5 6 7->4 5 6 7 0 1 2)中查找目标,返回下标,如果不存在则返回-1.
知识点:二分查找
难点:判断目标在左边[target,mid-1]还是[mid+1,end]-->用IsPossible(int start,int end,int target)判断。
AC代码:
class Solution {public: bool IsPossible(int start,int end,int target) { if(start==target||end==target) return true; if(start<end) { return(target>start&&target<end); }else if(start>end) { return(target>start||target<end); }else{ return false; } } int search(int A[], int n, int target) { int left=0,right=n-1; while(left<=right) { int mid=(left+right)/2; if(A[mid]==target) return mid; if(IsPossible(A[0],A[mid],target)) { right=mid-1;/*target在mid左边*/ } else { left=mid+1;/*target在mid右边*/ } } return -1; }};
0 0
- [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
- 用GDB调试程序(一)
- RocketMQ安装和小试
- Android getView中的position问题解决方案
- Deep Learning and Shallow Learning
- JNI设置C++与java的结合(2)
- [LeetCode]Search in Rotated Sorted Array
- 计算机视觉、机器学习相关领域论文和源代码大集合
- linux 线程切换效率与进程切换效率相差到底有多大?
- BitMap高效显示策略(三):使用内存缓存技术和BitmapFactory.Options.inBitmap参数
- lucene索引删除,恢复,更新
- android手机摄像:硬编码、软编码实验结果
- linux内核网络协议栈学习笔记:关于GRO/GSO/LRO/TSO等patch的分析和测
- poj1019 Number Sequence
- GDB调试指令