随笔- 509  文章- 0  评论- 151  阅读- 22万 

Find Minimum in Rotated Sorted Array

2015.1.22 07:07

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.

Solution:

  With no duplicates in the array, you'll find it easy to perform binary search on that position of the minimal element. Please see the code below for yourself.

  Total time complexity is O(log(n)). Space complexity is O(1).

Accepted code:

复制代码
 1 // 1AC, typical problem
 2 class Solution {
 3 public:
 4     int findMin(vector<int> &num) {
 5         int n = (int)num.size();
 6         
 7         if (num[0] < num[n - 1]) {
 8             return num[0];
 9         }
10         
11         int ll, mm, rr;
12         
13         ll = 0;
14         rr = n - 1;
15         while (rr - ll > 1) {
16             mm = ll + (rr - ll) / 2;
17             if (num[mm] > num[ll]) {
18                 ll = mm;
19             } else {
20                 rr = mm;
21             }
22         }
23         
24         return num[rr];
25     }
26 };
复制代码

 

 posted on   zhuli19901106  阅读(197)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示