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

[LintCode] Search in Rotated Sorted Array

时间:2017-11-13 11:35:15      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:ota   lintcode   may   val   style   ram   sum   div   range   

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.

Example

For [4, 5, 1, 2, 3] and target=1, return 2.

For [4, 5, 1, 2, 3] and target=0, return -1.

Challenge 

O(logN) time

 

A rotated sorted array has a split point where one side of this point is sorted, the other side is not.

 1 public class Solution {
 2     /** 
 3      *@param A : an integer rotated sorted array
 4      *@param target :  an integer to be searched
 5      *return : an integer
 6      */
 7     public int search(int[] A, int target) {
 8         if(A == null || A.length == 0)
 9         {
10             return -1;
11         }
12         return searchHelper(A, target, 0, A.length - 1);
13     }
14     
15     private int searchHelper(int[] A, int target, int startIdx, int endIdx)
16     {
17         if(startIdx > endIdx)
18         {
19             return -1;
20         }
21         
22         int mid = startIdx + (endIdx - startIdx) / 2;
23         
24         if(A[mid] == target)
25         {
26             return mid;
27         }
28         //right half sorted
29         else if(A[mid] < A[endIdx])
30         {
31             //if target in range of right half
32             if(target > A[mid] && target <= A[endIdx])
33             {
34                 return searchHelper(A, target, mid + 1, endIdx);
35             }
36             //search left half otherwise 
37             else
38             {
39                 return searchHelper(A, target, startIdx, mid - 1);
40             }
41         }
42         //left half sorted 
43         else
44         {
45             //if target in range of left half
46             if(target >= A[startIdx] && target < A[mid])
47             {
48                 return searchHelper(A, target, startIdx, mid - 1);
49             }
50             //search right half otherwise
51             else
52             {
53                 return searchHelper(A, target, mid + 1, endIdx);
54             }
55         }
56     }
57 }

 

 

Related Problems

Search in Rotated Sorted Array II

Search a 2D Matrix

[LintCode] Search in Rotated Sorted Array

标签:ota   lintcode   may   val   style   ram   sum   div   range   

原文地址:http://www.cnblogs.com/lz87/p/7494209.html

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