Skip to content

Commit 11ecbc7

Browse files
committed
Problem 154
1 parent e6096e3 commit 11ecbc7

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Problem 154: Find Minimum in Rotated Sorted Array II
3+
* Prompt: Suppose an array sorted in ascending order is rotated
4+
* at some pivot unknown to you beforehand.
5+
* (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
6+
* Find the minimum element. The array may contain duplicates.
7+
* Date: 07/25/2020
8+
*/
9+
class Solution {
10+
public int findMin(int[] nums) {
11+
int lo = 0;
12+
int hi = nums.length - 1;
13+
while (lo < hi)
14+
{
15+
int mid = lo + (hi - lo) / 2;
16+
if (nums[mid] < nums[hi])
17+
hi = mid;
18+
else if (nums[mid] > nums[hi])
19+
lo = mid + 1;
20+
else
21+
hi--;
22+
}
23+
return nums[lo];
24+
}
25+
}
26+
27+
/**
28+
* Notes: There are two situations to consider, one is with rotation,
29+
* and the other is without rotation. We use binary search to look
30+
* at which interval we need to look for the smallest number. If
31+
* all is with rotation, then we can just divide into two portions,
32+
* if mid < hi then use left, otherwise use right. However, once
33+
* we add the without rotation condition. Once we have mid == hi,
34+
* we run into a contradiction of how to deal with it between this
35+
* and the previous situation. So we can only do hi-- because we
36+
* know that this current one can be omitted (there are other same
37+
* ones in front of it. )
38+
*/

0-Binary-Search/Binary-Search.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,18 @@ class Solution {
4949

5050
---
5151

52+
### 154. Find Minimum in Rotated Sorted Array II
53+
54+
#### [解法一](154-Find-Minimum-in-Rotated-Sorted-Array-II.java):二分查找分三类
55+
56+
一共有两种情况,一种是中间某点有置换位置,另一种是完全没有置换位置。如果没有置换位置的话可以分两种情况,如果中间点比右边小则说明可以往左找(包括当前点),否则往右边找(不包括当前点,因为当前点比右边的大或者相等)。
57+
58+
但是如果中间有置换位置,则发现在两数相等的情况下需要往左找,和上一种情况中的往右找相矛盾。所以只能确定的是可以把右侧边界前移(因为前面有和这个数相同的数,所以这个数可以省去)。
59+
60+
![图解](https://raw.githubusercontent.com/YuqiZ2020/PicBed/master/img/20200725203018.png)
61+
62+
---
63+
5264
### 275. H-Index-II
5365
#### [解法一](275-H-Index-II.java):二分查找
5466
_时间复杂度:O(log(n)); 空间复杂度:O(1)_

0 commit comments

Comments
 (0)