leetcode--Search in Rotated Sorted Array

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.

public class Solution {
   /**
	 * modified the binary search.<br>
	 *when the array is rotated, we first find the minimum and then do binary search in appropriate subarray.<br>
	 * @param A  --Integer array, search in this array
	 * @param target --int, searched number	 *
	 * @return int. If the target is found, return the index, otherwise return -1.
	 * @author Averill Zheng
	 * @version 2014-06-05
	 * @since JDK 1.7
	 */
	public int search(int[] A, int target) {
		int length = A.length, index = -1;
		if(length > 0){
			int tempIndex = 0;
			if(A[0] <= A[length - 1]) //normal order
				tempIndex = Arrays.binarySearch(A, target);
				//index = (tempIndex >= 0) ? tempIndex : -1;
			else{ 
				//find the min first
				int min = findMin(A, 0, length - 1);
				
				if(target >= A[0])
					tempIndex = Arrays.binarySearch(A, 0, min, target);
				else
					tempIndex = Arrays.binarySearch(A, min, length, target);
			}
			index = (tempIndex < 0) ? -1 : tempIndex;
		}
		return index;	
	}
	public  int findMin(int[] A, int i, int j){
		int min = i, left = i, right = j;
		if(A[i] > A[j]){
			while(left < right - 1){
				int mid = left + (right - left) / 2;	
				if(A[left] < A[mid])
					left = mid;				
				else
					right = mid;			
			}
			min = (A[left] < A[right])? left : right; 
		}
		return min;
    }
}

 

leetcode online judge is also accepted the code if we use the linear search method to find the minimum as follows:

public int findMin(int[] A, int i, int j){
	int left = i, right = j; 
	while(left < right){
		if(A[left] > A[right])
			++left;
		else
			--right;
	}
	return left;
}

  

 

posted @ 2014-06-07 10:41  Averill Zheng  阅读(140)  评论(0编辑  收藏  举报