-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path35-search-insert-position.js
47 lines (41 loc) · 1.38 KB
/
35-search-insert-position.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
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var searchInsert = function(nums, target) {
// Iterate over each integer in sorted input array nums
for (let i = 0; i < nums.length; i++) {
// For each int in nums, check if it equals target
// If it does, return index of matching int
if (target === nums[i]) {
return i;
// Since the array is sorted, if it did NOT find
// a match in the array AND the target is less
// than the current integer at index i, this
// means that all the remaining numbers in the
// nums array are greater than the target (recall:
// it is sorted) - thus we can return the current
// index as this is where the target would go
} else if (nums[i] > target) {
return i;
}
}
// To cover the last case wherein the target is larger than
// every number in the input array, simply return the length
// of the array as the target would be pushed as the last index
// of the array
return nums.length;
};
/* Concise solution without comments:
var searchInsert = function(nums, target) {
for (let i = 0; i < nums.length; i++) {
if (target === nums[i]) {
return i;
} else if (nums[i] > target) {
return i;
}
}
return nums.length;
};
*/