Skip to content

Commit 4a8500c

Browse files
committed
✨ [153] Watched solution
1 parent d098877 commit 4a8500c

File tree

2 files changed

+52
-15
lines changed

2 files changed

+52
-15
lines changed

153/my_solution.js

+26-15
Original file line numberDiff line numberDiff line change
@@ -2,40 +2,51 @@
22
* @param {number[]} nums
33
* @return {number}
44
*/
5-
const findMin = (nums) => {
5+
const findMin = (nums) => { // O(log n)
66
// if (nums[0] < nums[nums.length - 1]) {
77
// console.log("nums.length - 1")
88
// console.log(nums.length - 1)
99
// return nums.length - 1;
1010
// }
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];
1313
// console.log(`l:${l}, r:${r}`)
1414

15-
while (l < r) {
16-
console.log(`l:${l}, r:${r}`)
15+
while (l <= r) {
1716
if (nums[l] < nums[r]) {
17+
min = Math.min(min, nums[l])
1818
break;
1919
}
2020

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]);
2226

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;
2633
}
34+
// // Find the mid of the new chunk
35+
// p = Math.ceil(((r - l) / 2) + l) - 1;
2736
}
2837

29-
count++;
30-
31-
console.log("count")
32-
console.log(count)
38+
console.log("min")
39+
console.log(min)
3340

3441
// if l==0 && l < r , count = nums.length
35-
return count;
42+
return min;
3643
};
3744

3845
// findMin([3, 4, 5, 1, 2]) // 3
3946
// findMin([4, 5, 6, 7, 0, 1, 2]) // 4
40-
findMin([11, 13, 15, 17]) // 4
47+
// findMin([11, 13, 15, 17]) // 4
4148
// 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

153/solution.js

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
const findMin = (nums) => {
6+
let l = 0, r = nums.length - 1, min = nums[0];
7+
8+
while (l <= r) {
9+
if (nums[l] < nums[r]) {
10+
min = Math.min(min, nums[l])
11+
break;
12+
}
13+
14+
let p = Math.ceil((r + l) / 2);
15+
16+
min = Math.min(min, nums[p]);
17+
18+
if (nums[l] <= nums[p]) {
19+
l = p + 1;
20+
} else {
21+
r = p - 1;
22+
}
23+
}
24+
25+
return min;
26+
};

0 commit comments

Comments
 (0)