File tree 1 file changed +37
-0
lines changed
0153-find-minimum-in-rotated-sorted-array
1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ // find the min. number in rotated sorted array; all the numbers are unique in the array; there are at least 1 item in the array
2
+
3
+ // approach: binary search - left&right pointer; use 2-pointers technique to find the sorted portion and return the leftmost value (min.value)
4
+
5
+ class Solution {
6
+ public int findMin (int [] nums ) {
7
+
8
+ // init left/right pointer
9
+ int left = 0 ;
10
+ int right = nums .length - 1 ;
11
+
12
+ int res = nums [0 ];
13
+
14
+ while (left <= right ) {
15
+
16
+ // if this portion is already sorted:
17
+ if (nums [left ] < nums [right ]) {
18
+
19
+ res = Math .min (res , nums [left ]);
20
+ break ;
21
+ }
22
+
23
+ // if this portion is not sorted: take the midpoint and contunue the binary search:
24
+ int mid = (left + right )/2 ;
25
+ res = Math .min (res , nums [mid ]);
26
+
27
+ // adjust the left/right pointer
28
+ if (nums [mid ] >= nums [left ]) {
29
+ left = mid +1 ;
30
+ } else {
31
+ right = mid -1 ;
32
+ }
33
+ }
34
+
35
+ return res ;
36
+ }
37
+ }
You can’t perform that action at this time.
0 commit comments