Wednesday, December 31, 2014

Leetcode 153: Find Minimum in Rotated Sorted Array



Problem:
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.

Analysis:
Similarly, we can easily check which part of the array is sorted and we just compare the lowest
element. Then, we continue to search the other part.

Code:
public class Solution {
    public int findMin(int[] num) {//[1],[2,1], [3,1,2]
        int left=0;
        int right=num.length-1;
        int min=Integer.MAX_VALUE;
        while(left<=right){
            int mid=(left+right)/2;
            if(num[left]<=num[mid]){
                min=Math.min(min,num[left]);
                left=mid+1;
            }else{
                right=mid;
            }
        }
        return min;
    }
}

1 comment:

  1. Borgata Hotel Casino & Spa - MapYRO
    Hotel 영천 출장안마 in Atlantic City has been cleaned, 광주광역 출장마사지 tested, and is 아산 출장샵 backed by our 90 day no questions asked returns 1xbet korean policy! Rating: 2.5 수원 출장안마 · ‎10 reviews

    ReplyDelete