35.搜索插入位置
小于 1 分钟
35.搜索插入位置
/*
* @lc app=leetcode.cn id=35 lang=typescript
*
* [35] 搜索插入位置,不存在时插入其升序位置,存在时返回其索引位置
*/
// @lc code=start
function searchInsert(nums: number[], target: number): number {
let num = 0;
if (nums.indexOf(target) === -1) {
if (nums[nums.length - 1] <= target) {
return nums.length;
}
for (let i = 0; i < nums.length; i++) {
nums.map((el, index) => {
if (target >= nums[index] && target <= nums[index + 1]) {
num = index + 1;
}
});
}
} else {
num = nums.indexOf(target);
}
return num;
}
console.log(searchInsert([1, 3, 5, 6], 7));
// @lc code=end
Loading...
