Search in Rotated Sorted Array -- leetcode
来源:互联网 发布:斑马梦龙网络计划 编辑:程序博客网 时间:2024/04/30 07:40
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.
版本一,递归实现
在leetcode上,实际执行时间为7ms。
算法基本思路依据为,将区间折半后,必有一半是递增的(左端点的值小于右端点的值)。
看要找的值在此区间中没,若在,在此区间继续搜索。否则,进入另一半区间。
class Solution {public: int search(int A[], int n, int target) { if (!n) return -1; bool first = false; const int mid = (n-1) / 2; if (A[mid] == target) return mid; else if ((A[0] <= target && target < A[mid])) first = true; else if (A[mid] < target && target <= A[n-1]) first = false; else if (A[0] > A[mid]) first = true; if (first) return search(A, mid, target); else { const int result = search(A+mid+1, n-mid-1, target); return result != -1 ? result + mid+1 : -1; } }};
版本2:非递归实现
其思路与上同。 只是将上面的代码加入了while循环。
执行时间也是7ms。
class Solution {public: int search(int A[], int n, int target) { int low = 0; int high = n - 1; while (low <= high) { bool first = false; const int mid = low + (high - low) / 2; if (A[mid] == target) return mid; else if ((A[0] <= target && target < A[mid])) first = true; else if (A[mid] < target && target <= A[n-1]) first = false; else if (A[0] > A[mid]) first = true; if (first) high = mid - 1; else low = mid + 1; } 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
- Linux改变文件或文件夹权限
- 最小费用最大流
- hdu1074--Doing Homework(状压dp)
- Linux命令-系统相关
- MFC学习笔记之VC++ Debug Assertion Failed! 错误(File: strex.cpp Line: 690)
- Search in Rotated Sorted Array -- leetcode
- struts2+jquery+json集成
- Linux命令-磁盘文件相关
- ImageNet Classification with Deep Convolutional Neural Networks 阅读理解及问题
- 构造器与静态工厂
- linux命令-文件权限相关
- 指针数组与数组指针的区别
- Navicat for Oracle 安装后连接配置问题(ORA-12541或者ORA-28547等)
- inux命令-用户相关