• 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;
    }
    

      

     

  • 相关阅读:
    LALR(1)语法分析生成器--xbytes
    <<摩托车修理技术与禅>>读书笔记
    xscript脚本
    CentOS安装Erlang
    TCP中close和shutdown之间的区别
    Erlang高阶函数
    深度学习小记
    mac平台打造犀利的Android Studio开发环境
    MAC中如何配置两套android-sdk环境
    Ubuntu虚拟机编译Android6.0总结
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3774364.html
Copyright © 2020-2023  润新知