首页 > 代码库 > Search in Rotated Sorted Array
Search in Rotated Sorted Array
Search in Rotated Sorted Array
Total Accepted: 22300 Total Submissions: 77945My SubmissionsSuppose 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.
给出排好序的数组,在某个pivot进行旋转,这样数组变成两段有序,并且第二段的最大值小于第一段的最小值。要求log(n)内找出target的位置。
思路1:找出第一段有序的末尾位置,然后判断在哪一段进行二分查找。
class Solution { public: int search(int A[], int n, int target) { int pivot = findPivot(A, n, target); if (-1 == pivot) { return -1; } if (target >= A[0] && target <= A[pivot]) { return binarySearch(A, 0, pivot, target); } if (pivot < n - 1) { return binarySearch(A, pivot + 1, n - 1, target); } return -1; } private: int findPivot(int A[], int n, int target) { int start = 0, end = n - 1; if (A[start] <= A[end]) { return end; } while (start <= end) { int middle = (start + end) / 2; if (middle + 1 <= n && A[middle] > A[middle + 1]) { return middle; } if (A[middle] >= A[start]) { start = middle + 1; } else { end = middle - 1; } } return -1; } int binarySearch(int A[], int start, int end, int target) { while (start <= end) { int middle = (start + end) / 2; if (target == A[middle]) { return middle; } else if (target > A[middle]) { start = middle + 1; } else { end = middle - 1; } } return -1; // not found } };这个思路是可以,只是有很多临界条件要考虑。
思路2:直接二分查找,要判断清楚在左边还是右边查找。
class Solution { public: int search(int A[], int n, int target) { int start = 0, end = n - 1; while (start <= end) { int middle = (start + end) / 2; if (target == A[middle]) { return middle; } if (A[middle] < A[end]) { if (target > A[middle] && target <= A[end]) { start = middle + 1; } else { end = middle - 1; } } else { if (target >= A[start] && target < A[middle]) { end = middle - 1; } else { start = middle + 1; } } } return -1; } };
Search in Rotated Sorted Array
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。