您的位置:首页 > 其它

在旋转数组中找最小的值

2016-06-16 14:59 183 查看
原题如下所示:


153. Find Minimum in Rotated Sorted Array

 My Submissions

Question
Editorial Solution

Total Accepted: 96116 Total
Submissions: 261936 Difficulty: Medium

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.

Subscribe to see which companies asked this question
public class Solution {
public int findMin(int[] nums) {
if (nums==null || nums.length==0) { return Integer.MIN_VALUE; }
int left = 0, right = nums.length-1;
while (left < right-1) { // while (left < right-1) is a useful technique
int mid = left + (right-left)/2;
if (nums[mid] > nums[right]) { left = mid; }
else { right = mid; }
}
if (nums[left] > nums[right]) { return nums[right]; }
return nums[left];
}
}

如上所示,每次与最右边的元素比较会避免很多特殊的情况,这是由最有元素的特殊性决定的,mid元素大于right说明当前处于较大的组中,当mid小于right元素的值则说明当前处于较小的组。而且有效的避免了完全导致,和完全未倒置的情况。当完全倒置时  每次与最右端比较持续右移,当完全未旋转时 持续左移。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: