标签:
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.
分析:
这道题给出了一个有序数组,找出数组中最小的元素,其实就是找出第一个小于最后一个元素出现的位置,
比如题中给出的 4 5 6 0 1 2 ,
最后一个元素为2,
只需要找出第一个小于2的元素出现的位置。
之所以不用第一个元素作为target,因为翻转数组有一种极限情况,那就是完全不翻转,就是0 1 4 5 6 7,
这种情况下如果用第一个元素作为target就会出错。
// find the first element that <= targrt, the last element is the target.
public class Solution { // find the first element that <= targrt, the last element is the target. public int findMin(int[] nums) { if (nums.length == 0){ return 0; } int start = 0, end = nums.length; int target = nums[nums.length - 1]; int mid; while (start + 1 < end){ mid = start + (end - start) / 2; if (nums[mid] <= target){ end = mid; }else{ start = mid; } } if (nums[start] <= target){ return nums[start]; }else{ return nums[end]; } } }
leetcode 153. Find Minimum in Rotated Sorted Array
标签:
原文地址:http://www.cnblogs.com/iwangzheng/p/5747627.html