• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Find Minimum in Rotated Sorted Array

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.

这道题跟Search in Rotated Sorted Array这道题很像,区别在于这道题不是找一个目标值,而是找最小值。所以与那道题的思路类似又有区别。类似在于同样是用binary search找目标区域,通过左边界和中间的大小关系来得到左边或者右边有序。区别在于这一次迭代不会存在找到target就终止的情况,iteration要走到 l > r 的情况才停止。所以这一次思路是确定中点哪一边有序之后,那一边的最小值就是最左边的元素。用这个元素尝试更新全局维护的最小值,然后迭代另一边。这样子每次可以截掉一半元素,所以最后复杂度等价于一个二分查找,是O(logn),空间上只有四个变量维护二分和结果,所以是O(1)。

 

 1 class Solution {
 2     public int findMin(int[] nums) {
 3         int res = Integer.MAX_VALUE;
 4         int l = 0, r = nums.length - 1;
 5         while (l <= r) {
 6             int m = (l + r) / 2;
 7             if (nums[m] >= nums[l]) {
 8                 // rotation is happened in the latter half
 9                 // [l, m] is in order
10                 res = Math.min(res, nums[l]);
11                 l = m + 1;
12             }
13             else {
14                 // rotation is happened in the first half
15                 // [m, r] is in order
16                 res = Math.min(res, nums[m]);
17                 r = m - 1;
18             }
19         }
20         return res;
21     }
22 }

 

posted @ 2014-11-22 10:40  neverlandly  阅读(459)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3