159.Find Minimum in Rotated Sorted Array

1.Description(Medium)

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e.,0 1 2 4 5 6 7might become4 5 6 7 0 1 2).

Find the minimum element.

Notice

You may assume no duplicate exists in the array.

Example

Given[4, 5, 6, 7, 0, 1, 2]return0

2.Code

注意这个题和一般的BS相反

找first position <=target(target 设置为最后一个数)

nums[mid]<target 向前找

nums[mid]>target 向后找

nums[mid]==target 向前找

注意最后肯定会返回一个值,所以直接else返回就行了。

public int findMin(int[] num) {
       if(num==null || num.length==0){
            return -1;
        }

        int start=0,end=num.length-1;
        int target=num[num.length-1];//set last number as the target,find first element<=target

        //find first element<=target
        while(start+1<end){
            int mid=start+(end-start)/2;

            if(num[mid]==target){
                end=mid;                
            }
            else if(num[mid]>target){
                start=mid;
            }
            else{
                end=mid;
            }
        }

        if(num[start]<=target){
            return num[start];
        }
        else{
            return num[end];
        }

Last updated