File tree Expand file tree Collapse file tree 2 files changed +16
-11
lines changed
solution/src/main/java/com/inuker/solution Expand file tree Collapse file tree 2 files changed +16
-11
lines changed Original file line number Diff line number Diff line change 7
7
public class FindMinimumInRotatedSortedArray {
8
8
9
9
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 ]) {
12
13
return nums [left ];
13
14
}
14
- int mid = left + (( right - left ) >> 1 ) ;
15
+ int mid = ( left + right ) / 2 ;
15
16
16
- if (nums [mid ] > nums [left ]) {
17
+ if (nums [mid ] >= nums [left ]) {
17
18
left = mid + 1 ;
18
- } else if (nums [mid ] < nums [right ]) {
19
- right = mid ;
20
19
} else {
21
- return Math . min ( nums [ left ], nums [ right ]) ;
20
+ right = mid ;
22
21
}
23
22
}
24
- return 0 ;
23
+ return nums [ left ] ;
25
24
}
26
25
}
Original file line number Diff line number Diff line change @@ -9,10 +9,10 @@ public class FindMinimumInRotatedSortedArrayII {
9
9
public int findMin (int [] nums ) {
10
10
int left = 0 , right = nums .length - 1 ;
11
11
12
- for ( ; left < right ; ) {
13
- int mid = left + (( right - left ) >> 1 ) ;
12
+ while ( left < right ) {
13
+ int mid = ( left + right ) / 2 ;
14
14
15
- if (nums [right ] > nums [left ]) {
15
+ if (nums [left ] < nums [right ]) {
16
16
return nums [left ];
17
17
}
18
18
@@ -21,6 +21,12 @@ public int findMin(int[] nums) {
21
21
} else if (nums [mid ] < nums [right ]) {
22
22
right = mid ;
23
23
} 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
+ */
24
30
left ++;
25
31
}
26
32
}
You can’t perform that action at this time.
0 commit comments