首页 > 代码库 > Leetcode:Search in Rotated Sorted Array
Leetcode:Search in Rotated Sorted Array
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.
思路:先遍历一遍数组,找出分割点,将数组分成low1~high1,low2~high2两个有序子数组,其中A[high2]<A[low1]。
如果A[low1]<=target,则在low1~high1区间二分查找;
如果A[low1]>target,则在low2~high2区间二分查找。
时间复杂度为O(logn + n)。
代码如下:
class Solution { public: int binSearch(int A[],int begin,int end,int target) { while(begin <= end) { int mid = begin + (end - begin) >> 1; if(A[mid] > target) end = mid - 1; else if(A[mid] < target) begin = mid + 1; else return mid; } return -1; } int search(int A[], int n, int target) { if(n == 0)return -1; int i = 0; while(i < n - 1 && A[i] < A[i + 1]) i++; if(i == n - 1) return binSearch(A,0,n - 1,target); if(i < n - 1) { int low1 = 0; int high1 = i; int low2 = i + 1; int high2 = n - 1; if(A[low1] <= target) { int idx = binSearch(A,low1,high1,target); if(idx >= 0)return idx; else return -1; } else { int idx = binSearch(A,low2,high2,target); if(idx >= 0)return idx; else return -1; } } } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。