Skip to content

Commit 8aa0674

Browse files
committed
fd
1 parent bc27ccf commit 8aa0674

File tree

2 files changed

+16
-11
lines changed

2 files changed

+16
-11
lines changed

solution/src/main/java/com/inuker/solution/FindMinimumInRotatedSortedArray.java

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,19 @@
77
public class FindMinimumInRotatedSortedArray {
88

99
public int findMin(int[] nums) {
10-
for (int left = 0, right = nums.length - 1; left >= 0 && left <= right; ) {
11-
if (nums[right] > nums[left]) {
10+
int left = 0, right = nums.length - 1;
11+
while (left < right) {
12+
if (nums[left] < nums[right]) {
1213
return nums[left];
1314
}
14-
int mid = left + ((right - left) >> 1);
15+
int mid = (left + right) / 2;
1516

16-
if (nums[mid] > nums[left]) {
17+
if (nums[mid] >= nums[left]) {
1718
left = mid + 1;
18-
} else if (nums[mid] < nums[right]) {
19-
right = mid;
2019
} else {
21-
return Math.min(nums[left], nums[right]);
20+
right = mid;
2221
}
2322
}
24-
return 0;
23+
return nums[left];
2524
}
2625
}

solution/src/main/java/com/inuker/solution/FindMinimumInRotatedSortedArrayII.java

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@ public class FindMinimumInRotatedSortedArrayII {
99
public int findMin(int[] nums) {
1010
int left = 0, right = nums.length - 1;
1111

12-
for ( ; left < right; ) {
13-
int mid = left + ((right - left) >> 1);
12+
while (left < right) {
13+
int mid = (left + right) / 2;
1414

15-
if (nums[right] > nums[left]) {
15+
if (nums[left] < nums[right]) {
1616
return nums[left];
1717
}
1818

@@ -21,6 +21,12 @@ public int findMin(int[] nums) {
2121
} else if (nums[mid] < nums[right]) {
2222
right = mid;
2323
} else {
24+
/**
25+
* 这里表示mid不在左单调区间,也不在右单调区间,有两种情况
26+
* 1,nums[mid] == nums[left],此时最小值肯定在left右边,有可能在mid左边,也可能在mid右边
27+
* 2,nums[mid] == nums[right],此时最小值肯定在left右边,但可能在mid右边,也可能在mid左边
28+
* 综上,肯定在left右边
29+
*/
2430
left++;
2531
}
2632
}

0 commit comments

Comments
 (0)