[Search] LeetCode rotation sorted array

[Problem] Suppose in accordance with the ascending order of the array was rotated in a previously unknown point.

(E.g., array [0,1,2,4,5,6,7] may become [4,5,6,7,0,1,2]).

Searching for a given target value, if the existence of the target array, its index returns, otherwise it returns -1.

You can assume that the array element does not exist in duplicate.
Your time complexity of the algorithm must be O (log n) level.

Example 1 : 
Input: the nums = [ 4 , . 5 , . 6 , . 7 , 0 , 1 , 2 ], target = 0 
Output: 4 
Example 2 : 
Input: the nums = [ 4 , . 5 , . 6 , . 7 , 0 , 1 , 2 ], target = . 3 
output: - . 1

[Thinking] is due to the rotation of the array is sorted, so we cut in half from the middle, half of which must be orderly, while the other half is a rotating array is sorted, split again or will generate an ordered and disordered array!
So we started the first half, the calculated mid, therefore:

1, if the (mid, r] orderly, it is determined that the target is not in the ordered array, if so, select the right part, l = mid + 1.

2, or [l, mid) ordered and then determines target, and start bounded.

3. Note: calculated using mid preferably l + (rl) >> 1, rather than the (l + r) >> 1, l + r because the type of data may exceed the boundaries! Cause unknown error.

class Solution {
 public :
     int Search (Vector < int > the nums &, int target) {
         int L = 0 , R & lt nums.size = () - . 1 ;
         the while (L <= R & lt) {
             int MID = L + (rl is an) / 2 ;
             IF (the nums [MID] == target)   return MID;
             IF (the nums [MID] <the nums [R & lt]) {    // If the right half of the ordered direct binary 
                IF (the nums [MID] <&& target target <= the nums [R & lt]) = MID + L . 1 ;
                 // if the target falls ordered part, then l = mid + 1
                the else   R & lt MID = - . 1 ; 
            } the else {   // if not ordered right half, the left half of it must be ordered 
                IF (the nums [MID]> target && target> the nums = [L]) = R & lt MID - . 1 ;
                 the else L = MID + . 1 ; 
            }   
        } 
        return - . 1 ; 
    } 
};

Guess you like

Origin www.cnblogs.com/zhudingtop/p/11540212.html