Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit b4d8d47

Browse files
author
zongyanqi
committed
add Easy_35_Search_Insert_Position
1 parent 63a956c commit b4d8d47

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Easy_35_Search_Insert_Position.js

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Given a sorted array and a target value, return the index if the target is found.
3+
* If not, return the index where it would be if it were inserted in order.
4+
*
5+
* You may assume no duplicates in the array.
6+
*
7+
* Here are few examples.
8+
* [1,3,5,6], 5 → 2
9+
* [1,3,5,6], 2 → 1
10+
* [1,3,5,6], 7 → 4
11+
* [1,3,5,6], 0 → 0
12+
*/
13+
14+
/**
15+
* @param {number[]} nums
16+
* @param {number} target
17+
* @return {number}
18+
*/
19+
var searchInsert = function (nums, target) {
20+
21+
var index = 0;
22+
for (var i = 0; i < nums.length; i++) {
23+
var temp = nums[i];
24+
if (target === temp) {
25+
return i;
26+
}
27+
else if (target > temp) {
28+
index++;
29+
} else {
30+
return index;
31+
}
32+
}
33+
return index;
34+
35+
};
36+
37+
console.log(searchInsert([1, 3, 5, 6], 5) == 2);
38+
console.log(searchInsert([1, 3, 5, 6], 2) == 1);
39+
console.log(searchInsert([1, 3, 5, 6], 7) == 4);
40+
console.log(searchInsert([1, 3, 5, 6], 0) == 0);
41+
console.log(searchInsert([1, 3, 5, 6], 100) == 4);

0 commit comments

Comments
 (0)