当前位置:网站首页>Find minimum in rotated sorted array
Find minimum in rotated sorted array
2022-06-23 09:35:00 【ruochen】
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.
The sequence is basically in order , Then use binary search . Suppose the sequence is n,s It's the starting subscript ,e Is the last subscript ,m Is the middle element subscript . There are three situations :
ns < ne
nm > ns > ne
nm < ne < ns
situation 1:ns < ne
0 1 2 4 5 6 7
This situation , Go straight back to ns. Because the sequence is ordered , Or just rotate once . If ns < ne, Indicates that there is no rotation . The smallest element is ns.
situation 2:nm > ns > ne
4 5 6 7 0 1 2
public int findMin(int[] nums) {
if (nums.length == 1) {
return nums[0];
}
if (nums.length == 2) {
return Math.min(nums[0], nums[1]);
}
int s = 0, e = nums.length - 1;
int m = (s + e) / 2;
if (nums[s] < nums[e]) {
return nums[s];
}
if (nums[m] > nums[s]) {
return findMin(Arrays.copyOfRange(nums, m + 1, e + 1));
}
return findMin(Arrays.copyOfRange(nums, s, m + 1));
}边栏推荐
- Sequential representation and implementation of sequencelist -- linear structure
- [geek Challenge 2019] hardsql
- RGB and CMYK color modes
- Redis学习笔记—持久化机制之RDB
- Difference between global shutter and roller shutter
- web--信息泄漏
- 披萨订购设计----简单工厂模式
- Kotlin Series 1: getting started with basics
- Bit binding
- 16. system startup process
猜你喜欢

swagger UI :%E2%80%8B

Cesium loading orthophoto scheme
Redis learning notes - data type: hash

swagger UI :%E2%80%8B

一个采用直接映射方式的32KB缓存......存储器课后习题
![[网鼎杯 2020 青龙组]AreUSerialz](/img/38/b67f7a42abec1cdaad02f2b7df6546.png)
[网鼎杯 2020 青龙组]AreUSerialz
Redis学习笔记—发布订阅
Redis learning notes - slow query analysis

Wechat applet: click the button to switch frequently, overlap the custom markers, but the value does not change
![[wangdingbei 2020 Qinglong formation]areuserialz](/img/38/b67f7a42abec1cdaad02f2b7df6546.png)
[wangdingbei 2020 Qinglong formation]areuserialz
随机推荐
mysql乐观锁与悲观锁
Redis学习笔记—Pipeline
ionic5錶單輸入框和單選按鈕
How should junior programmers who enter a small company improve themselves?
栈(Stack)的链式实现详解----线性结构
web--信息泄漏
RGB and CMYK color modes
Three methods to find the limit of univariate function -- lobida's rule and Taylor's formula
Getting started with cookies and sessions
[GYCTF2020]Blacklist
[極客大挑戰 2019]HardSQL
Cesium加载正射影像方案
36 krypton launched | cloud native database company "tuoshupai" completed a new round of strategic financing, and the valuation has reached the level of quasi Unicorn
Web -- Information Disclosure
UCOSII (learning notes)
一个采用直接映射方式的32KB缓存......存储器课后习题
Notes on using the coding code base
Redis学习笔记—持久化机制之RDB
披萨订购设计----简单工厂模式
Aiming at the overseas pet market, "grasshand" has developed an intelligent tracking product independent of mobile phones | early project