File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
find-minimum-in-rotated-sorted-array Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ input : array of integers
3
+ output : minimum element's value
4
+
5
+ 3 4 5 1 2
6
+ draw graph
7
+
8
+ 5
9
+ 4
10
+ 3
11
+ 2
12
+ 1
13
+ l r
14
+ l r
15
+ l r
16
+ --------------
17
+ 5
18
+ 4
19
+ 3
20
+ 2
21
+ 1
22
+ mid right
23
+ --------------
24
+ left < right ->> sorted.
25
+ left < mid ->> don't have to search range [left, mid]
26
+ mid > right ->> rotation point is between [mid, right];
27
+
28
+ solution 1) brute force
29
+ read the array
30
+
31
+ tc : O(n)
32
+ sc : O(1);
33
+
34
+ solution 2) binary search
35
+ do binary search, move pointers with descripted conditions
36
+ after binary search loop ends, the left pointer is the minimum element
37
+
38
+ tc : O(logn)
39
+ sc : O(1)
40
+ */
41
+
42
+ class Solution {
43
+ public int findMin (int [] nums ) {
44
+ int l = 0 ;
45
+ int r = nums .length - 1 ;
46
+ while (l < r ) {
47
+ int mid = (r - l ) / 2 + l ;
48
+ if (nums [mid ] < nums [r ]) {
49
+ r = mid ;
50
+ } else {
51
+ l = mid + 1 ;
52
+ }
53
+ }
54
+ return nums [l ];
55
+ }
56
+ }
You can’t perform that action at this time.
0 commit comments