|
2 | 2 | * @param {number[]} nums
|
3 | 3 | * @return {number}
|
4 | 4 | */
|
5 |
| -const findMin = (nums) => { |
| 5 | +const findMin = (nums) => { // O(log n) |
6 | 6 | // if (nums[0] < nums[nums.length - 1]) {
|
7 | 7 | // console.log("nums.length - 1")
|
8 | 8 | // console.log(nums.length - 1)
|
9 | 9 | // return nums.length - 1;
|
10 | 10 | // }
|
11 |
| - |
12 |
| - let l = 0, r = nums.length - 1, count = 0, min = 0; |
| 11 | + // let p = Math.ceil(nums.length / 2) - 1, l = 0, r = nums.length - 1, min = nums[p]; |
| 12 | + let l = 0, r = nums.length - 1, min = nums[0]; |
13 | 13 | // console.log(`l:${l}, r:${r}`)
|
14 | 14 |
|
15 |
| - while (l < r) { |
16 |
| - console.log(`l:${l}, r:${r}`) |
| 15 | + while (l <= r) { |
17 | 16 | if (nums[l] < nums[r]) {
|
| 17 | + min = Math.min(min, nums[l]) |
18 | 18 | break;
|
19 | 19 | }
|
20 | 20 |
|
21 |
| - count++; |
| 21 | + let p = Math.ceil((r + l) / 2); |
| 22 | + |
| 23 | + console.log(`l:${l}, r:${r}, p:${p}, nums[p]:${nums[p]}`) |
| 24 | + // L <= mid = they are the same chunk |
| 25 | + min = Math.min(min, nums[p]); |
22 | 26 |
|
23 |
| - if (nums[l] > nums[r]) { |
24 |
| - l++; |
25 |
| - r--; |
| 27 | + if (nums[l] <= nums[p]) { |
| 28 | + // Set L to the most right. |
| 29 | + l = p + 1; |
| 30 | + } else { |
| 31 | + // L > Mid, mid is in the R chunk |
| 32 | + r = p - 1; |
26 | 33 | }
|
| 34 | + // // Find the mid of the new chunk |
| 35 | + // p = Math.ceil(((r - l) / 2) + l) - 1; |
27 | 36 | }
|
28 | 37 |
|
29 |
| - count++; |
30 |
| - |
31 |
| - console.log("count") |
32 |
| - console.log(count) |
| 38 | + console.log("min") |
| 39 | + console.log(min) |
33 | 40 |
|
34 | 41 | // if l==0 && l < r , count = nums.length
|
35 |
| - return count; |
| 42 | + return min; |
36 | 43 | };
|
37 | 44 |
|
38 | 45 | // findMin([3, 4, 5, 1, 2]) // 3
|
39 | 46 | // findMin([4, 5, 6, 7, 0, 1, 2]) // 4
|
40 |
| -findMin([11, 13, 15, 17]) // 4 |
| 47 | +// findMin([11, 13, 15, 17]) // 4 |
41 | 48 | // findMin([3, 4, 5, 6, 7, 0, 1, 2]) // 1
|
| 49 | +// findMin([1]) // 1 |
| 50 | +// findMin([3, 1, 2]) // 1 |
| 51 | + |
| 52 | +findMin([2, 1]) // 1 |
0 commit comments