leetcode #154 in cpp
来源:互联网 发布:什么是网络公关 编辑:程序博客网 时间:2024/06/05 09:23
Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?Would this affect the run-time complexity? How and why?
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.
The array may contain duplicates.
Solution:The difference between this question and the previous question is that the rule that works in the previous question does not work here:if nums[i] > nums[j] then nums[i...j] wouldn't contain the pivot and thus can be dropped. One example is [4,1,2,3,4], i = 0, j = 4. If we apply the rule above, then nums[0....4] is determined as having no pivot. But that is not true. Thus when we have num[left boundary] == num[right boundary], we cannot give up this range. Instead we shrink the left boundary or right boundary by skipping the duplicates. This step would introduce O(n) into our algorithm.
Code:
class Solution {public: int findMin(vector<int>& nums) { int h = nums.size() - 1; int l = 0; int minn = INT_MAX; while(h>=l){ int mid = (h+l)/2; minn = min(nums[mid], minn); if(nums[mid] <= nums[h]){ if(nums[mid] == nums[h]){ while(h >= mid && nums[h] == nums[mid]){//skip duplicates h--; } }else{ minn = min(nums[mid], minn); h = mid - 1; } }else{ if(nums[mid] > nums[l]){ minn = min(nums[l], minn); l = mid + 1; }else{ while(l <= mid && nums[l] == nums[mid]){ l++; } } } } return minn; }};
0 0
- leetcode #154 in cpp
- leetcode #12 in cpp
- Leetcode #13 in cpp
- Leetcode #14 in cpp
- leetcode %15 in cpp
- leetcode #16 in cpp
- leetcode #17 in cpp
- leetcode #18 in cpp
- leetcode #20 in cpp
- leetcode #21 in cpp
- leetcode #22 in cpp
- leetcode #23 in cpp
- leetcode #24 in cpp
- leetcode #25 in cpp
- leetcode #26 in cpp
- leetcode #27 in cpp
- leetcode #28 in cpp
- leetcode #29 in cpp
- 面试
- sort-colors
- 表格拖动排序jquery-ui
- JavaScript中的jsonp(跨域请求)
- web开发一月总结
- leetcode #154 in cpp
- 滑动UITableViewCell出现多个按钮
- LeetCode 129. sum-root-to-leaf-numbers
- C语言中access函数
- jstl自定义函数标签---备忘录
- linux设备树的解释 - 总览
- Pow(x, n)
- Hyperion 安装部署过程
- 简单的动画效果 iOS新手笔记