Search in rotated sorted Array Total accepted:22300 Total submissions:77945 My submissions
Suppose a sorted array is rotated at some unknown to you beforehand.
(I. e .,0 1 2 4 5 6 7Might become4 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.
Returns an sorted array and rotates it in a shard. In this way, the array is sorted in two segments, and the maximum value of the second segment is smaller than the minimum value of the first segment. The target location must be located in log (n.
Train of Thought 1: Find the end position of the first segment, and then determine which segment to perform binary search.
Class solution {public: int search (int A [], int N, int target) {int rows = findpivot (A, N, target); If (-1 = Hangzhou) {return-1;} If (target> = A [0] & target <= A [random]) {return binarysearch (A, 0, random, target );} if (Response <n-1) {return binarysearch (A, response + 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 }};This idea is acceptable, but there are many critical conditions to consider.
Train of Thought 2: directly perform binary search. You need to determine whether to search on the left or right.
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