在旋转数组中找最小的值
2016-06-16 14:59
183 查看
原题如下所示:
My Submissions
Question
Editorial Solution
Total Accepted: 96116 Total
Submissions: 261936 Difficulty: Medium
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.
Subscribe to see which companies asked this question
public class Solution {
public int findMin(int[] nums) {
if (nums==null || nums.length==0) { return Integer.MIN_VALUE; }
int left = 0, right = nums.length-1;
while (left < right-1) { // while (left < right-1) is a useful technique
int mid = left + (right-left)/2;
if (nums[mid] > nums[right]) { left = mid; }
else { right = mid; }
}
if (nums[left] > nums[right]) { return nums[right]; }
return nums[left];
}
}
如上所示,每次与最右边的元素比较会避免很多特殊的情况,这是由最有元素的特殊性决定的,mid元素大于right说明当前处于较大的组中,当mid小于right元素的值则说明当前处于较小的组。而且有效的避免了完全导致,和完全未倒置的情况。当完全倒置时 每次与最右端比较持续右移,当完全未旋转时 持续左移。
153. Find Minimum in Rotated Sorted Array
My SubmissionsQuestion
Editorial Solution
Total Accepted: 96116 Total
Submissions: 261936 Difficulty: Medium
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.
Subscribe to see which companies asked this question
public class Solution {
public int findMin(int[] nums) {
if (nums==null || nums.length==0) { return Integer.MIN_VALUE; }
int left = 0, right = nums.length-1;
while (left < right-1) { // while (left < right-1) is a useful technique
int mid = left + (right-left)/2;
if (nums[mid] > nums[right]) { left = mid; }
else { right = mid; }
}
if (nums[left] > nums[right]) { return nums[right]; }
return nums[left];
}
}
如上所示,每次与最右边的元素比较会避免很多特殊的情况,这是由最有元素的特殊性决定的,mid元素大于right说明当前处于较大的组中,当mid小于right元素的值则说明当前处于较小的组。而且有效的避免了完全导致,和完全未倒置的情况。当完全倒置时 每次与最右端比较持续右移,当完全未旋转时 持续左移。
相关文章推荐
- logstash,nginx日志,grok pattern调试
- SharePoint 2013 CSOM 对象模型属性包
- Java集合---HashSet的源码分析
- 团队开发项目客户端——注册子系统的设计
- ios基本控件之UIAlertController
- C++读写Excel文件
- RAD 10.1多标签页bug
- H264视频压缩编码标准(四)
- 取消一个请求(Cancel)
- Git知识点总结
- 对Hongyang大神文章《Andoird 自定义ViewGroup实现竖向引导界面》的阅读笔记
- Android activity 切换动画
- Android3D动画翻转效果
- 查询能力(SIP OPTIONS)
- awk用法:取列表最后一列
- awk用法:取列表最后一列
- SPRING MVC 的请求参数获取的几种方法
- H264视频压缩编码标准(三)
- Linode vps使用日志
- [Java] 通过域名获取IP地址的方法与作用