Search in Rotated Sorted Array

Q:

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.

还是使用二分法,通过比较最左边,中间以及target的大小关系可以确认是向左走或向右走。当然,这是数组中无重复的情形,如果有重复还需要考虑的更加完善。

A:

 1 class Solution {
 2 public:
 3     int search(int A[], int n, int target) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (n < 0) return -1;
 7         int begin = 0;
 8         int end = n - 1;
 9         
10         while (begin <= end) {
11             int pos = (begin + end) / 2;
12             if (A[pos] == target) {
13                 return pos;
14             }
15             if (A[begin] == target) return begin;
16             
17             if (A[pos] < target) {
18                 if (A[begin] > target) {
19                     begin = pos + 1;
20                 } else {
21                     if (A[begin] <= A[pos]) {
22                         begin = pos + 1;
23                     } else {
24                         end = pos - 1;
25                     }
26                 }
27             } else {
28                 if (A[begin] < target) {
29                     end = pos - 1;
30                 } else {
31                     if (A[begin] <= A[pos]) {
32                         begin = pos + 1;
33                     } else {
34                         end = pos - 1;
35                     }
36                 }
37             }
38         }
39         return -1;
40     }
41 };

 

posted @ 2013-06-15 16:20  dmthinker  阅读(98)  评论(0)    收藏  举报