当前位置:网站首页>【每日一题】【leetcode】25. 数组-旋转数组的最小数字
【每日一题】【leetcode】25. 数组-旋转数组的最小数字
2022-08-10 15:04:00 【aneutron】
题目
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。 难易程度:easy
示例 1:
输入:[3,4,5,1,2] 输出:1
示例 2:
输入:[2,2,2,0,1] 输出:0
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
方法一
分析
首先,题目中给出的数组是部分有序。最小的元素就是旋转点:
- 前后元素都比他大
- 前边的子数组是递增的
- 后边的子数组是递增的
因此,直观的解法就是遍历,找到第一个位置:numbers[l] < numbers[r]。 时间复杂度:O(N) 空间复杂度:O(1)
代码
class Solution {
public:
int minArray(vector<int>& numbers) {
int l = 0, r = numbers.size() - 1;
while (l < r) {
if (numbers[l] >= numbers[r]) {
l++;
} else {
break;
}
}
return numbers[l];
}
};方法二
分析
题意已经明确,原始数组是由有序数组旋转生成,设最小值的索引为mid,则[0, mid)和[mid, size)是两个有序数组。查找最小值本身就是搜索问题。本题题意抽取出如下两点:
- 有序
- 查找
因此,可以考虑二分搜索算法,判断条件如下;
numbers[mid] > numbers, 则l = mid + 1numbers[mid] < numbers, 则r = midnumbers[mid] == numbers,特殊的点就在这儿,此时,最小值只能在[l, r),因此r--
时间复杂度:O(logN) 空间复杂度:O(1)
代码
class Solution {
public:
int minArray(vector<int>& numbers) {
int l = 0, r = numbers.size() - 1;
while (l < r) {
int mid = ((r - l) >> 1) + l;
if (numbers[mid] > numbers[r]) {
l = mid + 1;
} else if (numbers[mid] < numbers[r]) {
r = mid;
} else {
r--;
}
}
return numbers[r];
}
};边栏推荐
- 5G NR MIB Detailed Explanation
- MySQL批量更新与批量更新多条记录的不同值实现方法
- Detailed understanding of anonymous functions and all built-in functions (Part 2)
- Yi Gene|In-depth review: epigenetic regulation of m6A RNA methylation in brain development and disease
- const修饰的指针变量(详解)
- 26、压缩及解压缩命令
- 产品说明丨如何使用MobPush快速创建应用
- 【吴恩达来信】强化学习的发展!
- Common conventions such as common SQL and API interfaces
- 常见SQL、API接口等常见约定
猜你喜欢

Cesium Quick Start 4-Polylines primitive usage explanation

容器化 | 在 S3 实现定时备份

秒杀项目收获

一个 ABAP 工具,能打印系统里某个用户对 BSP 应用的浏览历史记录

Appium for APP automation testing

Cesium快速上手4-Polylines图元使用讲解

SWIG tutorial "two"

“低代码”编程或将是软件开发的未来

Oracle database backup DMP file is too big, what method can be split into multiple DMP when backup?

持续集成实战 —— Jenkins自动化测试环境搭建
随机推荐
Yann LeCun转推:参数减少50倍,性能还更好,MetaAI推出Atlas信息检索模型
Recommend a few had better use the MySQL open source client, collection!
Oracle database backup DMP file is too big, what method can be split into multiple DMP when backup?
scala basics
Yi Gene|In-depth review: epigenetic regulation of m6A RNA methylation in brain development and disease
MySQL batch update and batch update method of different values of multiple records
产品说明丨如何使用MobPush快速创建应用
"NIO Cup" 2022 Nioke Summer Multi-School Training Camp 7
常见SQL、API接口等常见约定
头脑风暴:目标和
NPM - Cannot read properties of null (reading 'pickAlgorithm') 解决方案
使用Uiautomator2进行APP自动化测试
Brainstorm: Goals and
丁香园
fatal error C1083 无法打开包括文件'io.h' No such file
pm2 static file service
Boss raises salary!Look at my WPF Loading!!!
Go Context基本使用
Detailed understanding of anonymous functions and all built-in functions (Part 2)
一个 ABAP 工具,能打印系统里某个用户对 BSP 应用的浏览历史记录