zoukankan      html  css  js  c++  java
  • 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;
    }
    

      

     

  • 相关阅读:
    ASP.NET MVC5写.php路由匹配时的问题 ASP.NET MVC 4 在 .NET 4.0 与.NET 4.5 的專案範本差異
    asp.net mvc上传头像加剪裁功能介绍
    图片延迟加载实现
    c#中多线程访问winform控件的若干问题
    C# WinForm实现控件拖动实例介绍
    C# 实现对窗体(Form)换肤
    C#读写txt文件的两种方法介绍
    C#实现JSON序列化与反序列化介绍
    高效的VS调试技巧
    SQL 添加字段和默认值脚本
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3774364.html
Copyright © 2011-2022 走看看