Skip to content

Commit 7daa008

Browse files
author
baochau.dinh
committed
js-concepts: leetcode prob.153 - find minimum in rotated sorted array
1 parent 18581c6 commit 7daa008

File tree

2 files changed

+32
-14
lines changed
  • LeetCode
    • 153. Find Minimum in Rotated Sorted Array

2 files changed

+32
-14
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
var detectShift = function(nums) {
2+
let left = 0, right = nums.length - 1;
3+
let ans = 0;
4+
while (left < right) {
5+
let mid = left + Math.floor((right - left) / 2);
6+
if (nums[mid] > nums[left]) {
7+
ans = mid;
8+
left = mid;
9+
} else {
10+
right = mid;
11+
}
12+
}
13+
14+
return ans;
15+
}
16+
17+
var findMin = function(nums) {
18+
if (nums.length === 1) return nums[0]
19+
20+
let shiftIndx = detectShift(nums);
21+
let first = nums.slice(0, shiftIndx + 1)[0];
22+
let second = nums.slice(shiftIndx + 1, nums.length)[0];
23+
return Math.min(first, second);
24+
};
25+
26+
console.log(findMin([1]));

LeetCode/33. Search in Rotated Sorted Array/index.js

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -30,23 +30,15 @@ const detectShift = function (nums) {
3030

3131
const search = function (nums, target) {
3232
let shiftIndx = detectShift(nums);
33-
let result = -1;
34-
if (nums[shiftIndx] === target) {
35-
return shiftIndx;
36-
}
37-
let first = binarySearch(nums.slice(0, shiftIndx + 1), target);
38-
let second = binarySearch(nums.slice(shiftIndx + 1, nums.length), target);
33+
console.log('shiftIndx: ', shiftIndx);
34+
let first = nums.slice(0, shiftIndx + 1)[0];
35+
let second = nums.slice(shiftIndx + 1, nums.length)[0];
3936

4037
if (first === -1 && second === -1) {
41-
return result;
38+
return false;
4239
} else {
43-
if (first !== -1) {
44-
return first;
45-
}
46-
if (second !== -1) {
47-
return shiftIndx + second + 1;
48-
}
40+
return true;
4941
}
5042
}
5143

52-
console.log(search([4, 5, 6, 7, 0, 1, 2], 2));
44+
console.log(search([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1], 2));

0 commit comments

Comments
 (0)