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.,
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];
}
}
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,
0 1 2 4 5 6 7might 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];
}
}
相关文章推荐
- HDU 1039 判断字符串的合法性
- HIbernate聚合函数和分组查询(学习笔记)
- 深入理解js数组的sort排序
- 【克罗地亚】NIKOLA
- android framebuffer adb pull
- openSession()和getCureentSession()的区别
- 一个表单提交操作的编码格式问题
- 1036: [ZJOI2008]树的统计Count 【树链剖分】【点权:单点更新区间求值】
- 剑指offer面试题7(java实现)
- 网龙现场笔试电话面试经历
- Android菜单详解(五)——使用XML生成菜单
- viewDidLoad, viewWillDisappear, viewWillAppear等区别及各自的加载顺序
- Windows-DB2 9.7安装图解
- POJ1004 Financial Management【保留小数】
- 根据Schema写出XML文档四部曲
- Xlint:invalidAbsoluteTypeName
- android 设计模式之单例模式详解
- C / C++中保留小数精度
- css 字体
- js获取参数丢失0