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

      

     

  • 相关阅读:
    Python学习笔记-常用内置函数
    Python练习-高阶函数-2018.12.03
    Python练习-生成器、迭代器-2018.12.01
    Python练习-列表生成式-2018.11.30
    Python练习-迭代-2018.11.28
    Python练习-循环及切片-2018.11.27
    FortiGate端口聚合配置
    FortiGate路由模式--静态地址线路上网配置
    方位电话批量配置教程
    Python学习笔记(七)
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3774364.html
Copyright © 2020-2023  润新知