您的位置:首页 > 其它

Leetcode no. 153

2016-05-28 16:42 246 查看
153. 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.

public class Solution {
public int findMin(int[] nums) {
if (nums.length ==0) return 0;
if (nums.length ==1) return nums[0];
int left=0, right= nums.length-1;
while (left<right){
int center= (left+right)/2;
if (center>0 && nums[center]<nums[center-1])
return nums[center];
if (nums[center]>=nums[left] && nums[center]>nums[right])
left= center+1;
else right= center-1;
}
return nums[left];
}
}

better one:

public class Solution {
public int findMin(int[] nums) {
if (nums.length ==0) return 0;
if (nums.length ==1) return nums[0];
int left=0, right= nums.length-1;
while (left<right-1){
int center= (left+right)/2;
if (nums[center]>nums[right]) left= center;
else right= center;
}
return (nums[left]>nums[right]) ? nums[right] : nums[left];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: