LeeCode每日刷题12.8

搜索插入位置

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

请必须使用时间复杂度为 O(log n) 的算法。

示例 1:

输入: nums = [1,3,5,6], target = 5
输出: 2

示例 2:

输入: nums = [1,3,5,6], target = 2
输出: 1

示例 3:

输入: nums = [1,3,5,6], target = 7
输出: 4

提示:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums 为 无重复元素 的 升序 排列数组
  • -104 <= target <= 104
class Solution {
    public int searchInsert(int[] nums, int target) {
              int index=0;
//1.找索引2.找插入位置
        for (int i = 0; i < nums.length ; i++) {
//找是否有目标值,有就返回索引
            if (nums[i]==target){
                return i;
            }
            //找到插入位置
            if (target>=nums[i]){
                index=i+1;
            }
        }
//返回插入的索引
return index;

    }
}

相关推荐

  1. LeeCode每日12.8

    2023-12-08 15:12:04       51 阅读
  2. LeetCode每日.09(128.最长连续序列)

    2023-12-08 15:12:04       51 阅读
  3. LeetCode 每日 2023/12/18-2023/12/24

    2023-12-08 15:12:04       49 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-08 15:12:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-08 15:12:04       101 阅读
  3. 在Django里面运行非项目文件

    2023-12-08 15:12:04       82 阅读
  4. Python语言-面向对象

    2023-12-08 15:12:04       91 阅读

热门阅读

  1. 附录1、vuepress中的Markdown语法

    2023-12-08 15:12:04       63 阅读
  2. 利用 Python 进行数据分析实验(三)

    2023-12-08 15:12:04       53 阅读
  3. 利用 Python 进行数据分析实验(五)

    2023-12-08 15:12:04       57 阅读
  4. docker网络

    2023-12-08 15:12:04       46 阅读
  5. VBA 数组写入ACCESS

    2023-12-08 15:12:04       62 阅读
  6. 数据结构的存储方式

    2023-12-08 15:12:04       55 阅读
  7. Kotlin(十三) 延迟初始化和密封类

    2023-12-08 15:12:04       58 阅读
  8. rpc服务、微服务架构、分布式应用是什么

    2023-12-08 15:12:04       60 阅读
  9. 人工智能助力医疗:科技护航健康未来

    2023-12-08 15:12:04       58 阅读