LeetCode153:Find Minimum in Rotated Sorted Array
来源:互联网 发布:什么贵金属软件好 编辑:程序博客网 时间:2024/06/06 01:10
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.
不知道这道题为什么难度是Medium,感觉蛮简单的。
只需要找到第一个大于它后面的数,它后面的数就是旋转排序数组中最小的数。将返回结果初始化为数组中的第一个元素,这样就可以将结果统一起来。时间复杂程度是O(N)。
runtime:4ms
class Solution {public: int findMin(vector<int>& nums) { int result=nums[0]; auto iter=nums.begin(); for(;iter!=nums.end()-1;iter++) { if(*iter>*(iter+1)) { result=*(iter+1); break; } } return result; }};
然后看了下Discuss,发现了一个使用二分查找思想的代码,漫有意思的,也有分析。以后在碰到排序好的数组进行了一些变形或一些附加说明时注意使用二分查找的思想。时间复杂程度是O(logN)。链接
In this problem, we have only three cases.
Case 1. The leftmost value is less than the rightmost value in the list: This means that the list is not rotated. e.g> [1 2 3 4 5 6 7 ]
Case 2. The value in the middle of the list is greater than the leftmost and rightmost values in the list. e.g> [ 4 5 6 7 0 1 2 3 ]
Case 3. The value in the middle of the list is less than the leftmost and rightmost values in the list. e.g> [ 5 6 7 0 1 2 3 4 ]
As you see in the examples above, if we have case 1, we just return the leftmost value in the list. If we have case 2, we just move to the right side of the list. If we have case 3 we need to move to the left side of the list.
Following is the code that implements the concept described above.
int findMin(vector<int>& nums) { int left = 0, right = nums.size() - 1; while(left < right) { if(nums[left] < nums[right]) return nums[left]; int mid = (left + right)/2; if(nums[mid] > nums[right]) left = mid + 1; else right = mid; } return nums[left];}
- LeetCode153:Find Minimum in Rotated Sorted Array
- [LeetCode153]Find Minimum in Rotated Sorted Array
- leetcode153. Find Minimum in Rotated Sorted Array
- leetcode153---Find Minimum in Rotated Sorted Array(求最小者)
- LeetCode153—Find Minimum in Rotated Sorted Array
- LeetCode153. Find Minimum in Rotated Sorted Array如何用五行代码解决它
- Find Minimum in Rotated Sorted Array
- [LeetCode] Find Minimum in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array
- Leetcode: Find Minimum in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array
- leetcode :Find Minimum in Rotated Sorted Array
- LeetCode:Find Minimum in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array II
- HHUC-2015-dfs专讲①,A:ring road
- Redis安装【centos7】
- iOS 使用百度地图地图画成功了,但是没有图层显示问题解决。
- Sitemesh
- java中的clone()方法的研究---(7)如何编写正确的clone()方法:Date, Timestamp
- LeetCode153:Find Minimum in Rotated Sorted Array
- Qt图形框架资料05
- Android Studio如何集成Genymotion
- 性能测试面试题汇总(一)
- 编程能力与编程年龄
- 第十八章 TFTLCD显示实验
- Qt图形框架资料06
- urllib2的Openers和handlers
- Struts 2中的constant详解