Skip to content

Commit 7cc9d0c

Browse files
committed
Time: 0 ms (100.00%), Space: 42.1 MB (51.00%) - LeetHub
1 parent 993f048 commit 7cc9d0c

File tree

1 file changed

+37
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)