lintcode-62-搜索旋转排序数组
2017-07-03 12:59
417 查看
62-搜索旋转排序数组
假设有一个排序的按未知的旋转轴旋转的数组(比如,0 1 2 4 5 6 7 可能成为4 5 6 7 0 1 2)。给定一个目标值进行搜索,如果在数组中找到目标值返回数组中的索引位置,否则返回-1。
你可以假设数组中不存在重复的元素。
样例
给出[4, 5, 1, 2, 3]和target=1,返回 2给出[4, 5, 1, 2, 3]和target=0,返回 -1
挑战
O(logN) time标签
领英 数组 排序数组 二分法 优步 脸书思路
用二叉搜索。每次都把数组分成两半,判别哪一半是排过序的。如果待查元素在排过序的那一半,那么用二叉搜索。如果在另一半,那么我们递归地在这一半里继续查找。code
class Solution { /** * param A : an integer ratated sorted array * param target : an integer to be searched * return : an integer */ public: int search(vector<int> &A, int target) { // write your code here int low = 0, high = A.size()-1, size = A.size(), mid = 0; if(size <= 0) { return -1; } while(low <= high) { mid = (high + low) / 2; if(A[mid] == target) { return mid; } if(A[mid] >= A[low]) { if(A[low] <= target && target < A[mid]) { high = mid - 1; } else { low = mid + 1; } } else { if(A[mid] < target && target <= A[high]) { low = mid + 1; } else { high = mid - 1; } } } return -1; } };
相关文章推荐
- LintCode 62 搜索旋转排序数组
- LintCode 62 搜索旋转排序数组
- lintcode :search in rotated sorted array 搜索旋转排序数组
- LintCode:搜索旋转排序数组
- [Lintcode] 搜索旋转排序数组 II Search in Rotated Sorted Array II
- lintcode-63-搜索旋转排序数组 II
- [LintCode] 搜索旋转排序数组 Search in Rotated Sorted Array
- LintCode : 搜索旋转排序数组
- [Lintcode] Search in Rotated Sorted Array II 搜索旋转排序数组 II
- 搜索旋转排序数组 查看运行结果 ——LintCode
- LintCode-搜索旋转排序数组 II
- LintCode:搜索旋转排序数组
- lintcode-搜索旋转排序数组-62
- lintcode-搜索旋转排序数组II-63
- 62 - 搜索旋转排序数组
- LintCode 63 搜索旋转排序数组 II
- LintCode-搜索旋转排序数组
- *[Lintcode]搜索旋转排序数组
- Lintcode 搜索旋转排序数组 II
- 搜索旋转排序数组 II