Find the Minimum Element in A sorted and Rotated Array
2016-01-20 22:43
567 查看
Find the minimum element in a sorted and rotated array
A sorted array is rotated at some unknown point, find the minimum element in it.Following solution assumes that all elements are distinct.
Examples
Input: {5, 6, 1, 2, 3, 4} Output: 1 Input: {1, 2, 3, 4} Output: 1 Input: {2, 1} Output: 1
A simple solution is to traverse the complete array and find minimum. This solution requires Θ(n) time.
We can do it in O(Logn) using Binary Search. If we take a closer look at above examples, we can easily figure out following pattern: The minimum element is the only element whose previous element is greater than it. If there is no such element, then there is
no rotation and first element is the minimum element. Therefore, we do binary search for an element which is smaller than the previous element. We strongly recommend you to try it yourself before seeing the following are C and Java implementations.
C/C++
Java
Output:
The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1 The minimum element is 1
How to handle duplicates?
It turned out that duplicates can’t be handled in O(Logn) time in all cases. Thanks to Amit
Jain for inputs. The special cases that cause problems are like {2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 1, 2} and {2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2}. It doesn’t look possible to go to left half or right half by doing constant number of comparisons at the middle.
Following is an implementation that handles duplicates. It may become O(n) in worst case though.
C
Java
Output:
The minimum element is 1 The minimum element is 0 The minimum element is 1 The minimum element is 3 The minimum element is 0 The minimum element is 1 The minimum element is 0
This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
相关文章推荐
- 减少HTTP请求之合并图片详解(大型网站优化技术)
- [Swift开发实战]-闭包
- UML图中类之间的关系
- Maven私服的搭建
- MySQL中的Multi-Range Read优化
- linux查看进程的启动时间
- Multiple annotations found at this line: - ArtifactTransferException: Could not transfer artifact o
- Magic Spheres
- 如何用angularjs制作一个完整的表格之二__表格分页功能
- 适配器模式例子
- 着相
- Android-Tips
- test
- C语言 CRC32校验算法
- 服务器端架构,前端服务器与客户端随机负载平衡
- Find a Peak Element
- Deep Learning论文笔记之(四)CNN卷积神经网络推导和实现
- 画画板
- Xshell下漂亮的开发环境配置
- 进击的图表-看图学知识