【leetcode】Search in Rotated Sorted Array (hard)
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.
思路:二分搜索,每次去掉一半的错误选项。
注意,每次 l = m + 1, r = m - 1 防止无限循环。
int search(int A[], int n, int target) { int l = 0, r = n - 1; while(l <= r) //注意有等号 { int m = (l + r) / 2; if(A[m] == target) return m; if(A[l] <= A[m] && A[m] <= A[r]) //顺序的 { if(A[m] > target) r = m - 1; else l = m + 1; } else if(A[l] >= A[m] && A[m] <= A[r]) //开头转到了左半部分 { if(A[m] < target && target <= A[r]) //在右半部分 l = m + 1; else r = m - 1; } else //开头转到了右半部分 { if(A[l] <= target && target <= A[m]) //在左半部分 r = m - 1; else l = m + 1; } } return -1; }
大神简约版写法:去掉一半选项时的思路不同
int search(int A[], int n,int target) { int lo = 0; int hi = n - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (A[mid] == target) return mid; if (A[lo] <= A[mid]) { if (target >= A[lo] && target < A[mid]) { hi = mid - 1; } else { lo = mid + 1; } } else { if (target > A[mid] && target <= A[hi]) { lo = mid + 1; } else { hi = mid - 1; } } } return -1; }