LeetCode Search in Rotated Sorted Array solution, leetcoderotated
Suppose an array sorted in ascending order is rotated at some unknown
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.
Chinese:
Suppose there is an array in order to rotate by unknown axis of rotation (for example, 0 1 2 4 5 6 7 may become 4 5 6 7 0 1 2 ).
If you find the target value in the array and return the index position in the array, otherwise-1 is returned.
Solution:
The main idea is binary search. Although it is a rotating array, it is still satisfied. After finding the mid value, you can determine whether the mid value is greater than start to exclude half of the value of the array.
// The main idea is to use the public class Solution {public int search (int [] A, int target) {if (A = null |. length = 0) {return-1;} int start = 0; int end =. length-1; int mid; while (start + 1 <end) {mid = start + (end-start)/2; if (A [mid] = target) {return mid;} if (A [start] <A [mid]) {if (A [start] <= target & target <= A [mid]) {end = mid;} else {start = mid;} else {if (A [mid] <= target & target <= A [end]) {start = mid;} else {end = mid ;}} if (A [start] = target) {return start ;}if (A [end] = target) {return end;} return-1 ;}}