博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Find Minimum in Rotated Sorted Array
阅读量:7294 次
发布时间:2019-06-30

本文共 2020 字,大约阅读时间需要 6 分钟。

As explained in the Solution tag, the key to solving this problem is to use invariants. We set two pointers: l for the left and r for the right. One key invariant is nums[l] > nums[r]. If this invariant does not hold, then we know the array has not been rotated and the minimum is justnums[l]. Otherwise, we reduce the search range by a half each time via comparisons betweennums[l], nums[r] and nums[(l + r) / 2], denoted as nums[mid]:

  1. If nums[mid] > nums[r], then mid is in the first larger half and r is in the second smaller half. So the minimum will be right to mid, update l = mid + 1;
  2. If nums[mid] <= nums[r], then the minimum is at least nums[mid] and elements right tomid cannot be the minimum. So update r = mid (note that it is not mid - 1 since midmay also be the index of the minimum).

When l == r or the invariant does not hold, we have found the answer, which is just nums[l].

Putting these togerther, we have the following codes.


C (0 ms)

1 int findMin(int* nums, int numsSize) {2     int l = 0, r = numsSize - 1;3     while (l < r && nums[l] > nums[r]) {4         int mid = (l & r) + ((l ^ r) >> 1);5         if (nums[mid] > nums[r]) l = mid + 1;6         else r = mid; 7     }8     return nums[l];9 }

C++ (4 ms)

1 class Solution { 2 public: 3     int findMin(vector
& nums) { 4 int l = 0, r = nums.size() - 1; 5 while (l < r && nums[l] > nums[r]) { 6 int mid = (l & r) + ((l ^ r) >> 1); 7 if (nums[mid] > nums[r]) l = mid + 1; 8 else r = mid; 9 }10 return nums[l];11 }12 };

Python (48 ms)

1 class Solution: 2     # @param {integer[]} nums 3     # @return {integer} 4     def findMin(self, nums): 5         l, r = 0, len(nums) - 1 6         while l < r and nums[l] > nums[r]: 7             mid = (l & r) + ((l ^ r) >> 1) 8             if nums[mid] > nums[r]: 9                 l = mid + 110             else:11                 r = mid12         return nums[l]

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4658749.html

你可能感兴趣的文章
哈哈,好一个 uri,
查看>>
LVM扩容
查看>>
三:简单工厂模式
查看>>
正则表达式元字符
查看>>
【vue系列】elementUI 穿梭框右侧获取当前选中项的值的思路
查看>>
laravel and lumen 软删除操作
查看>>
数据集---Zachary's karate club---等
查看>>
Django之Form组件
查看>>
jquery validate.js 不能验证
查看>>
请教Ado.Net按文本读取CSV/Txt文件时,如何禁止将内容转换成数字
查看>>
电子电路基础——电感、磁珠
查看>>
Django tutorial part2
查看>>
loj10098 分离的路径
查看>>
超级详细找CALL写CALL教程[转]
查看>>
蓝桥杯:基础练习 特殊的数字
查看>>
Cairngorm3中文简介
查看>>
数据结构练手05 关于堆的up策略和down策略实现
查看>>
python-排序算法 冒泡和快速排序
查看>>
JAVA jdbc(数据库连接池)学习笔记(转)
查看>>
c#调用webservices
查看>>