LeetCode 153.Find Minimum in Rotated Sorted Array(M)(P)

题目:

Suppose an array sorted in ascending order 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.

思路:

1.题目中指出sorted array,find target使用二分法。

2.分为以下三种情况

(1)数组只有一个元素:nums[0]即为最小值。

(2)数组不是rotated sorted array,退化为sorted array:nums[0]即为最小值。

(3)数组是rotated sorted array:nums[start] > nums[end]:

a:nums[mid]大于nums[start].

b:nums[mid]小于nums[start].

代码:

 1 public class Solution {
 2     public int findMin(int[] nums) {
 3         int start = 0,end = nums.length-1,mid = 0;
//length equals 1;
4 if(nums.length == 1){ 5 return nums[0]; 6 }
//is rotated sorted array;
7 while(nums[start] > nums[end] && start + 1 < end){ 8 mid = start + (end - start)/2; 9 if(nums[mid] > nums[start]){ 10 start = mid; 11 }else if(nums[mid] < nums[start]){ 12 end = mid; 13 } 14 }
//is not rotated sorted array;
15 if(nums[start] < nums[end]){ 16 return nums[start]; 17 } 18 return nums[end]; 19 } 20 }

 

posted @ 2017-03-30 16:18  程序媛家  阅读(174)  评论(0编辑  收藏  举报