码迷,mamicode.com
首页 > 其他好文 > 详细

(33)Search in Rotated Sorted Array

时间:2015-02-09 17:42:52      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

 1 public class SearchRotatedSortedArray {
 2     public static int search(int[] A, int target) {
 3         int start = 0;
 4         int end = A.length - 1;
 5         int mid;
 6 
 7         while (start + 1 < end) {
 8             mid = start + (end - start) / 2;
 9             if (A[mid] == target) {
10                 return mid;
11             }
12             if (A[start] < A[mid]) {
13                 // situation 1, red line
14                 if (A[start] <= target && target <= A[mid]) {
15                     end = mid;
16                 } else {
17                     start = mid;
18                 }
19             } else {
20                 // situation 2, green line
21                 if (A[mid] <= target && target <= A[end]) {
22                     start = mid;
23                 } else {
24                     end = mid;
25                 }
26             }
27         } // while
28 
29         if (A[start] == target) {
30             return start;
31         }
32         if (A[end] == target) {
33             return end;
34         }
35         return -1;
36     }
37 
38     public static void main(String[] args) {
39         int[] a = {
40                 3,4, 5, 6, 7, 0, 1, 2
41         };
42         System.out.println(search(a, 1));
43     }
44 }

 

https://oj.leetcode.com/problems/search-in-rotated-sorted-array/

 

(33)Search in Rotated Sorted Array

标签:

原文地址:http://www.cnblogs.com/luochuanghero/p/4281818.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!