Skip to content

Commit 2b8d742

Browse files
committed
Add solution 153
1 parent 5dd4f1b commit 2b8d742

File tree

3 files changed

+90
-0
lines changed

3 files changed

+90
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ Complete solutions to Leetcode problems, updated daily.
3535
| 062 | [Unique Paths](https://github.com/yanglbme/leetcode/tree/master/solution/062.Unique%20Paths) | `Array`, `Dynamic Programming` |
3636
| 063 | [Unique Paths II](https://github.com/yanglbme/leetcode/tree/master/solution/063.Unique%20Paths%20II) | `Array`, `Dynamic Programming` |
3737
| 082 | [Remove Duplicates from Sorted List II](https://github.com/yanglbme/leetcode/tree/master/solution/082.Remove%20Duplicates%20from%20Sorted%20List%20II) | `Linked List` |
38+
| 153 | [Find Minimum in Rotated Sorted Array](https://github.com/yanglbme/leetcode/tree/master/solution/153.Find%20Minimum%20in%20Rotated%20Sorted%20Array) | `Array`, `Binary Search` |
3839

3940

4041
### Hard
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
## 寻找旋转排序数组中的最小值
2+
### 题目描述
3+
4+
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
5+
6+
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
7+
8+
请找出其中最小的元素。
9+
10+
你可以假设数组中不存在重复元素。
11+
12+
示例 1:
13+
```
14+
输入: [3,4,5,1,2]
15+
输出: 1
16+
```
17+
18+
示例 2:
19+
```
20+
输入: [4,5,6,7,0,1,2]
21+
输出: 0
22+
```
23+
24+
### 解法
25+
利用两个指针 p,q 指示数组的首尾两端,若 nums[p] <= nums[q],说明数组呈递增趋势,返回 nums[p];否则判断 nums[p] 与 nums[mid] 的大小,从而决定新的数组首尾两端,循环二分查找。
26+
27+
```java
28+
class Solution {
29+
public int findMin(int[] nums) {
30+
int n = nums.length;
31+
if (n == 1) {
32+
return nums[0];
33+
}
34+
35+
int p = 0;
36+
int q = n - 1;
37+
38+
39+
int mid = p + ((q - p) >> 1);
40+
41+
while (p < q) {
42+
if (nums[p] <= nums[q]) {
43+
break;
44+
}
45+
46+
if (nums[p] > nums[mid]) {
47+
q = mid;
48+
} else {
49+
p = mid + 1;
50+
}
51+
52+
mid = p + ((q - p) >> 1);
53+
}
54+
55+
return nums[p];
56+
57+
}
58+
}
59+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public int findMin(int[] nums) {
3+
int n = nums.length;
4+
if (n == 1) {
5+
return nums[0];
6+
}
7+
8+
int p = 0;
9+
int q = n - 1;
10+
11+
int mid = p + ((q - p) >> 1);
12+
13+
while (p < q) {
14+
if (nums[p] <= nums[q]) {
15+
break;
16+
}
17+
18+
if (nums[p] > nums[mid]) {
19+
q = mid;
20+
} else {
21+
p = mid + 1;
22+
}
23+
24+
mid = p + ((q - p) >> 1);
25+
}
26+
27+
return nums[p];
28+
29+
}
30+
}

0 commit comments

Comments
 (0)