Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode
033. Search in rotated Sorted Array (hard)
links:
Title: https://leetcode.com/problems/search-in-rotated-sorted-array/
Code (GitHub): Https://github.com/illuz/leetcode
Test Instructions:
Find a number in an ordered array that has been rotated.
For example 4 5 6 7 0 1 2
, a "rotated ordered array".
Analysis:
This is the distortion of the pure binary search.
Because the rotation is not good positioning, so when looking for the time can be judged whether an interval is completely ordered or has been rotated, and then classified discussion.
Code:
C++:
Class Solution {Public:int search (int a[], int n, int target) {int left = 0, right = N;while (left! = right) {int mid = (l EFT + right)/2;if (A[mid] = target) return mid;if (A[mid] >= A[left]) {//[Left~mid] is unrotated sortedif (A[left] & lt;= Target && Target < A[mid]) right = Mid;elseleft = mid + 1;} else {//[mid~right] is unrotated sortedif (A[mid] < target && target <= a[right-1]) left = mid + 1;elserig HT = mid;}} return-1;}};
[Leetcode] 033. Search in rotated Sorted Array (hard) (C + +)