-
Notifications
You must be signed in to change notification settings - Fork 20
/
SearchInsertPosition.js
67 lines (59 loc) · 1.36 KB
/
SearchInsertPosition.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* Given a sorted array and a target value, return the index if the target is found. If not,
* return the index where it would be if it were inserted in order.
* You may assume no duplicates in the array.
* Here are few examples.
*
* [1,3,5,6], 5 → 2
* [1,3,5,6], 2 → 1
* [1,3,5,6], 7 → 4
* [1,3,5,6], 0 → 0
*
* Accepted.
*/
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
let searchInsert = function (nums, target) {
if (nums == null || nums.length === 0) {
return 0;
}
for (let i = 0; i < nums.length; i++) {
if (nums[i] === target) {
return i;
} else if (nums[i] < target) {
if ((i + 1 < nums.length && nums[i + 1] > target)
|| (i + 1 === nums.length)) {
return i + 1;
}
}
}
return 0;
};
if (searchInsert([1], 0) === 0) {
console.log("pass")
} else {
console.error("failed")
}
if (searchInsert([1, 3, 5, 6], 5) === 2) {
console.log("pass")
} else {
console.error("failed")
}
if (searchInsert([1, 3, 5, 6], 2) === 1) {
console.log("pass")
} else {
console.error("failed")
}
if (searchInsert([1, 3, 5, 6], 7) === 4) {
console.log("pass")
} else {
console.error("failed")
}
if (searchInsert([1, 3, 5, 6], 0) === 0) {
console.log("pass")
} else {
console.error("failed")
}