Skip to content

Commit af7d350

Browse files
committed
35 - Search Insert Position Complete
1 parent 44bbeb8 commit af7d350

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

35-searchInsertPosition.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number}
5+
*/
6+
var searchInsert = function (nums, target) {
7+
const binarySearchInsert = (arr, target, startingIndex) => {
8+
const middleIndex = Math.floor(arr.length / 2);
9+
if (arr[middleIndex] === target) {
10+
return startingIndex + middleIndex;
11+
}
12+
if (arr.length === 1) {
13+
if (target < arr[middleIndex]) return startingIndex;
14+
return startingIndex + 1;
15+
}
16+
17+
if (target < arr[middleIndex]) {
18+
return binarySearchInsert(
19+
arr.splice(0, middleIndex),
20+
target,
21+
startingIndex
22+
);
23+
} else {
24+
return binarySearchInsert(
25+
arr.splice(middleIndex),
26+
target,
27+
startingIndex + middleIndex
28+
);
29+
}
30+
};
31+
32+
return binarySearchInsert(nums, target, 0);
33+
};
34+
35+

0 commit comments

Comments
 (0)