算法热题:旋转数组的最小数字
每日简短一刷,保持手感系列
题目:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
示例 1:输入:[3,4,5,1,2]输出:1
示例 2:输入:[2,2,2,0,1]输出:0
从题干直接 get 到关键字递增排序的数组,脑袋自然而然的得出此题需要用上二分法。
但是这又不是正常的二分,它只是部分有序,分界点就是我们需要得到的答案即最小数字。我们可以利用部分有序这个条件来进行二分的判断,利用二分逐步缩小搜索的范围。
- 当 numbers[mid] > numbers[right] 的时候,说明此时的 mid 在递增的前半部分,所以
left = mid + 1
- 当 numbers[mid] < numbers[right] 的时候,说明此时的 mid 是在被旋转的后半部分,所以
right = mid
- 当 numbers[mid] == numbers[right] 的时候,不清楚在哪,只要缩小查询的访问即可,
right--
解答如下:
classSolution{
publicintminArray(int[] numbers){
int left = 0, right = numbers.length - 1;
while (left < right) {
int mid = left + right >> 1;
if(numbers[mid] > numbers[right]) {
left = mid + 1;
} elseif (numbers[mid] < numbers[right]) {
right = mid;
} else {
right--;
}
}
return numbers[right];
}
}
时间复杂度O(logn),空间复杂度O(1)
一道简单题,边界值不清楚的可以画画图。
点击阅读原文即可练习。
添加微信:yes_oba,备注算法,即可进算法学习群。
关键词
算法
时候
数组的最小
部分
示例
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。