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
).
Find the minimum element.
You may assume no duplicate exists in the array.
tag : binary search
//思路与前两天的题一样,即用middle的值与边缘值作比较,从而判断pivot是在middle的左或右 //进而找到有序的一半数组,在这一半数组中找到最小的元素,再移动边缘 public class Solution { public int findMin(int[] nums) { int result = Integer.MAX_VALUE; int left = 0; int right = nums.length - 1; while(left <= right){ int middle = (left + right) / 2; if(nums[middle] < nums[right]){ //说明middle在pivot的右边,m-r段有序 if(nums[middle] < result){ //num[m]是m-r段最小的元素了 result = nums[middle]; } right = middle - 1; }else{ //题目指明无重复,此情况则l-m段有序 if(nums[left] < result){ result = nums[left]; } left = middle + 1; //关于while循环的终止,当循环到达left=middle时, } //无论如何下次会left>right从而终止循环 } return result; } }