Skip to content

Commit 6ebd1db

Browse files
committed
feat : find-minimum-in-rotated-sorted-array
1 parent cf1c998 commit 6ebd1db

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
}

0 commit comments

Comments
 (0)