图解「剑指Offer」之旋转数组的最小数字
source link: https://www.cxyxiaowu.com/463.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
图解「剑指Offer」之旋转数组的最小数字
剑指offer 2年前 0 2.8K
点击蓝色“五分钟学算法”关注我哟
加个“星标”,天天中午 12:15,一起学算法
作者 | 程序员小吴
来源 | 五分钟学算法
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
请找出其中最小的元素。
你可以假设数组中不存在重复元素。
示例 1:
输入: [3,4,5,1,2]
输出: 1
示例 2:
输入: [4,5,6,7,0,1,2]
输出: 0
最直接的方法是使用 暴力法:搜索整个数组,找到其中的最小元素,这样的时间复杂度是 O(N),其中 N 是给定数组的大小。
这道题目可以使用 二分搜索 的思想进行解决。
-
找到数组的中间元素 mid。
-
如果中间元素 > 数组第 low 个元素,则在 mid 右边搜索变化点。
-
如果中间元素 < 数组第 high 个元素,则在 mid 左边搜索变化点。
//author:程序员小吴
class Solution {
public int findMin(int[] nums) {
int low = 0, high = nums.length - 1;
while (low < high) {
if (nums[low] < nums[high]) return nums[low];
int mid = low + (high - low) / 2;
if (nums[mid] > nums[high]){
low = mid + 1;
} else{
high = mid;
}
}
return nums[low];
}
}
复杂度分析
- 时间复杂度:O(logN) 。
- 空间复杂度:O(1)。
数组、二分法、排序
— 完 —
Recommend
-
4
一文横扫数组基础知识旋转数组分为左旋转和右旋转两类,力扣 189 题为右旋转的情况,今日分享的为左旋转。给定一个数组,将数组中的元素向左旋转 k 个位置,其中 ...
-
7
图解剑指 offer 第二题: 替换空格 剑指offer...
-
0
图解「剑指Offer」之二维数组中的查找 剑指offer...
-
4
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从...
-
2
图解「剑指Offer」之使用栈实现队列 剑指offer...
-
2
JZ-006-旋转数组的最小数字发布于 10 月 26 日旋转数组的最小数字把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
-
8
剑指 Offer 11. 旋转数组的最小数字 ❤️来自专栏《LeetCode基础算法题》 欢迎订阅❤️ Table of Contents 🍓 博客主页: 作者主页 🍓 简介:JAVA领域优质创作者...
-
3
#yyds干货盘点# 解决剑指offer:数字在升序数组中出现的次数 原创 97的风
-
7
#yyds干货盘点# 解决剑指offer:左旋转字符串 原创 97的风 2022-05-30 10...
-
6
剑指 Offer 04. 二维数组中的查找 在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK