LeetCode Find Minimum in Rotated Sorted Array

题目描述: https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/

题目大意: 给定一个排好序的数组,从数组的任意一点开始,将数组旋转,例如:原数组[0,1,2,4,5,6,7],从4 旋转,得到[4,5,6,7,0,1,2],查找旋转后的数组中,最小的元素。对于给的例子,答案是0

思路:二分查找可解,对于给定的right,left ,mid = (right+left)/2 。若num[mid]>num[right],由题意知,最小的元素在从num[mid+1]到num[right]之间;若num[mid]<num[right],则最小的元素在从num[left]到num[mid]之间


package Find_Minimum_in_Rotated_Sorted_Array;

public class Solution {
	
	int binarySearch(int[] num){
		int left = 0,right = num.length-1;
		while(left < right){
			int mid = (left + right) / 2;
			if(num[mid]>num[right]){
				left = mid+1;
			}
			else if(num[mid]<num[right]){
				right = mid;
			}
		}
		return right;
	}
	public int findMin(int[] num){
		if(num==null || num.length ==0) 
			return -1;
		if(num[0]<num[num.length-1])
			return num[0];
		int ans = binarySearch(num);
		return num[ans];
	}
/**	public static void main(String[] args){
		int[] num = new int[]{5,6,7,0,1,2,3,4};
		System.out.println(new Solution().findMin(num));
	}
	**/
}


你可能感兴趣的:(LeetCode Find Minimum in Rotated Sorted Array)