File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
find-minimum-in-rotated-sorted-array Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ // Approach 2: binary search
2+ // Time Complexity: ✅ O(log n)
3+ // Space Complexity: O(1)
4+
5+ function findMin ( nums : number [ ] ) : number {
6+
7+ let left = 0
8+ let right = nums . length - 1
9+
10+ while ( left < right ) {
11+
12+ const mid = Math . floor ( ( left + right ) / 2 )
13+
14+ if ( nums [ mid ] > nums [ right ] ) {
15+ // the min must be to the right of mid
16+ left = mid + 1
17+ } else {
18+ // the mins could be mid or to the left
19+ right = mid
20+ }
21+ }
22+
23+ return nums [ left ]
24+ } ;
25+
26+
27+ // Approach 1:
28+ // Time Complexity: ❌ O(n)
29+ // Space Complexity: O(1)
30+
31+ // function findMin(nums: number[]): number {
32+ // // input: an array of length n sorted in ascending order
33+ // // rotate: a[n-1], a[0], ..., a[n-2]
34+ // // time complexity allowed: O(log n)
35+
36+ // let first = nums[0];
37+ // let last = nums[nums.length - 1];
38+ // let cnt = 0;
39+
40+ // while (first > last) {
41+ // first = last;
42+ // cnt += 1;
43+ // last = nums[nums.length - 1 - cnt];
44+ // }
45+
46+ // return first;
47+ // }
48+
You can’t perform that action at this time.
0 commit comments