记录九——搜索插入位置

搜索插入位置

题:给出一个排序好的数组nums和一个目标值target,如果数组中存在该目标值,返回该目标值的索引。若数组中没有该目标值,返回该目标值应该插入位置的索引。
Input: [1,3,5,6], 5
Output: 2


Input: [1,3,5,6], 2
Output: 1


Input: [1,3,5,6], 7
Output: 4


Input: [1,3,5,6], 0
Output: 0


思路:遍历一遍该数组,将目标值与数组中的每一个元素做比较,判断是否存目标值,若存在,返回索引,若不存在,判断是在哪两个索引元素中间,返回索引。
代码:

class Solution {
    public int searchInsert(int[] nums, int target) {
        int index = 0;
        if(nums[0] == target) return index;
        if(nums[nums.length - 1] < target) return nums.length ;
        for(int i = 1; i < nums.length;i++){
            if(nums[i] == target){
                index = i ; 
            }
            if(target > nums[i - 1] && target < nums[i]){
                index = i ;
            }
        }
        return index;
    }
}

还是要多思考,多动手。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值