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

[LintCode] 159 Find Minimum in Rotated Sorted Array

时间:2017-04-25 11:38:34      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:end   return   style   min   ==   element   dup   lin   class   

Description
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.

Notice

You may assume no duplicate exists in the array.


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

4/24/2017

算法班

不需要跟特定值比较,while里面判断只有2个分支。

 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         // write your code here
 8         if (nums == null || nums.length == 0) return -1;
 9         int start = 0, end = nums.length - 1;
10         
11         while (start + 1 < end) {
12             int mid = start + (end - start) / 2;
13             if (nums[mid] < nums[end]) {
14                 end = mid;
15             } else {
16                 start = mid;
17             }
18         }
19         return nums[start] < nums[end]? nums[start]: nums[end];
20     }
21 }

 

[LintCode] 159 Find Minimum in Rotated Sorted Array

标签:end   return   style   min   ==   element   dup   lin   class   

原文地址:http://www.cnblogs.com/panini/p/6760750.html

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