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
public class Solution { /** *@param A : an integer rotated sorted array *@param target : an integer to be searched *return : an integer */ public int search(int[] A, int target) { // write your code here if(A == null || A.length == 0) return -1; int left = 0; int right = A.length - 1; return search(A, target, left, right); } public int search(int[] A, int target, int left, int right){ if(left > right) return -1; if(left == right){ if(A[left] == target) return left; else return -1; } int mid = left + (right - left) / 2; if(A[mid] == target) return mid; if(A[mid] > target){ if(A[mid] > A[left]){ int index1 = search(A, target, left, mid - 1); int index2 = search(A, target, mid + 1, right); if(index1 == -1 && index2 == -1) return -1; else if(index1 == -1) return index2; else return index1; } else{ return search(A, target, left, mid - 1); } } else{ if(A[mid] > A[left]){ return search(A, target, mid + 1, right); } else{ int index1 = search(A, target, left, mid - 1); int index2 = search(A, target, mid + 1, right); if(index1 == -1 && index2 == -1) return -1; else if(index1 == -1) return index2; else return index1; } } } }
时间: 2024-12-24 04:11:16