首页 > 试题广场 >

搜索插入位置

[编程题]搜索插入位置
  • 热度指数:440 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

你可以假设数组中无重复元素。

示例1

输入

[1,3,5,6],5

输出

2
示例2

输入

[1,3,5,6],2

输出

1
示例3

输入

[1,3,5,6],7

输出

4
示例4

输入

[1,3,5,6],0

输出

0
遍历一次,如果小于等于数组索引值,那么直接返回数组,如果遍历完成则返回数组长度。牛客的一个[1,1,1,1,1,1],1用例, 预期为2,明显答案应该是0,LeetCode上就完全通过
发表于 2020-12-09 22:29:28 回复(0)
leetcode上秒过的题目,到了就只过了14个测试用例,我很费解
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 
 * @param nums int整型一维数组 
 * @param target int整型 
 * @return int整型
 */
 function searchInsertPosition( nums ,  target ) {
    // write code here
    let index = nums.indexOf(target)
    if(index !== -1){
        return index 
    }else{
        return [...nums,target].sort((a,b) => a-b).indexOf(target)
    }
}
module.exports = {
    searchInsertPosition : searchInsertPosition
};

发表于 2022-04-11 15:34:09 回复(0)
function searchInsertPosition( nums ,  target ) {
    const len = nums.length;
    for(let i = 0 ; i < len ; i++){
        if(nums[i] >=  target) return i
    }
    return len
    // write code here
}
module.exports = {
    searchInsertPosition : searchInsertPosition
};

真的是不明白为什么错,这垃圾编辑器真的是醉了
发表于 2021-08-16 17:54:04 回复(0)
function searchInsertPosition( nums ,  target ) {
    var index = ""
            if(nums.indexOf(target)>-1){
                index = nums.indexOf(target)
               return index
                 
            }else{
                nums.unshift(target)
                nums.sort(function(a , b){
                    return a-b
                })
                index = nums.indexOf(target)
                return index
            }
    // write code here
}

本题先用indexof判断数组中是否存在target目标值,如果存在,直接返回索引值,如果不存在,将target加入到数组中,再用sort排序,之后再返回索引值。不过不明白,题目说不考虑重复,为何用例要用[1,1,1,1,1,1]???
发表于 2020-12-17 08:55:24 回复(1)