[LintCode] 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.

Example

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

 

 1 public class Solution {
 2     /**
 3      * @param nums: a rotated sorted array
 4      * @return: the minimum number in the array
 5      */
 6     public int findMin(int[] nums) {
 7         return findMinHelper(nums, 0, nums.length - 1);
 8     }
 9     
10     private int findMinHelper(int[] nums, int startIdx, int endIdx)
11     {
12         if(endIdx - startIdx <= 1)
13         {
14             return nums[startIdx] < nums[endIdx] ? nums[startIdx] : nums[endIdx];
15         }
16         
17         int mid = startIdx + (endIdx - startIdx) / 2;
18         //right half not sorted, min value must be in the right half
19         //nums[mid] can't be the minimum 
20         if(nums[mid] > nums[endIdx])
21         {
22             return findMinHelper(nums, mid + 1, endIdx);
23         }
24         //nums[mid] <= nums[endIdx]
25         else
26         {
27             return findMinHelper(nums, startIdx, mid);
28         }
29     }
30 }

 

 

 

Related Problems

Find Minimum in Rotated Sorted Array II

Search in Rotated Sorted Array II

posted @ 2017-11-13 06:15  Review->Improve  阅读(141)  评论(0编辑  收藏  举报