码迷,mamicode.com
首页 > 其他好文 > 详细

Find Minimum in Rotated Sorted Array

时间:2015-03-08 11:39:23      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

Find Minimum 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).

Find the minimum element.

You may assume no duplicate exists in the array.

思路:

  变形后的二分查找

我的代码:

技术分享
public class Solution {
 public int findMin(int[] num) {
        if(num == null || num.length == 0) return -1;
        int left = 0;
        int right = num.length - 1;
        while(left + 1 < right)
        {
            int mid = (left + right)/2;
            int leftVal = num[left];
            int rightVal = num[right];
            int midVal = num[mid];
            if(leftVal <= midVal && midVal < rightVal)   return num[left];
            else if(midVal > rightVal)  left = mid;
            else right = mid;
        }
        if(num[left] <= num[right]) return num[left];
        else return num[right];
    }
}
View Code

学习之处;

  此种方法是改种后的二分查找,常规二分查找 left <= right left = mid - 1 or right = mid + 1,而此时变形为left = mid, right = mid,这样的话,如果判断条件还是left<=right,则无法跳出循环了,所以只能是left + 1 < right 

Find Minimum in Rotated Sorted Array

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4321363.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!