LeetCode33 Search in Rotated Sorted Array

Problem:

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.

Analysis:

Binary search

Code:

 1 class Solution{
 2 public:
 3     int search(int A[], int n, int target){
 4         int first = 0;
 5         int last = n;
 6         while (first != last){
 7             int mid = first + (last - first) / 2;
 8             if (A[mid] == target)
 9                 return mid;
10             if (A[first] <= A[mid]){
11                 if (A[first] <= target&&target < A[mid])
12                     last = mid;
13                 else
14                     first = mid + 1;
15             }
16             else{
17                 if (A[mid] < target&&target <= A[last - 1])
18                     first = mid + 1;
19                 else
20                     last = mid;
21             }
22         }
23         return -1;
24     }
25 };

 

posted on 2015-04-09 19:26  Jasonzhang398  阅读(200)  评论(0编辑  收藏  举报

导航