Java算法每日一题——搜索插入位置

文章目录

  • 二.搜索插入位置
    • [2.1 需求描述](#2.1 需求描述)
    • [2.2 代码实现](#2.2 代码实现)
      • [2.2.1 解法一](#2.2.1 解法一)
      • [2.2.2 解法二](#2.2.2 解法二)

二.搜索插入位置

2.1 需求描述

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

请必须使用时间复杂度为 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

2.2 代码实现

2.2.1 解法一

java 复制代码
public class Test35 {
    public static void main(String[] args) {
        int[] nums ={1,3,5,6};
         int target =5;
        int i = searchInsert(nums, target);
        System.out.println(i);//2

 
    }
    // 第一种解法;二分查找法基础本
    public static int searchInsert(int[] nums, int target) {
        int start = 0;
        int end = nums.length-1;
        while (start <= end){
            int mid = (start + end) >>> 1;
            if(target < nums[mid]){
                end = mid - 1;
            }else if (nums[mid] < target){
                start = mid + 1;
            }else {
                return mid;
            }
        }
        return start;
    }

}

2.2.2 解法二

java 复制代码
public class Test35 {
    public static void main(String[] args) {
      
        int[] nums ={1,3,5,6};
        int target =5;
        
        int i1 = binarySearchLeftmost(nums, target);
        System.out.println(i1);

    }
 
    // 第二种解法:二分查找法leftmost
    public static int binarySearchLeftmost(int[] arr, int target){
        // 起始索引
        int start = 0;
        // 末尾索引
        int end = arr.length-1;

        // start索引和end索范围内有东西执行查找
        while (start <= end){
            // 定义中间索引
            int mid = (start +end)>>>1;
            // 目标函数 小于 中间值
            if (target <= arr[mid] ){
                end = mid - 1;
            }else {
                start = mid + 1;
            }
        }
        //循环结束,假如找到在数组中找到目标值则返回最左边的查找目标值索引
        //如果没有找到返回的是目标值要插入的位置。
        //总的来说返回的是 >= target的最靠左索引
        return start;
    }
    // BinarySearch()  结束
}
相关推荐
Gerardisite1 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
Want5951 小时前
C/C++跳动的爱心①
c语言·开发语言·c++
coderxiaohan2 小时前
【C++】多态
开发语言·c++
gfdhy2 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
闲人编程2 小时前
Python的导入系统:模块查找、加载和缓存机制
java·python·缓存·加载器·codecapsule·查找器
百***06012 小时前
SpringMVC 请求参数接收
前端·javascript·算法
weixin_457760002 小时前
Python 数据结构
数据结构·windows·python
Eiceblue2 小时前
通过 C# 将 HTML 转换为 RTF 富文本格式
开发语言·c#·html
故渊ZY2 小时前
Java 代理模式:从原理到实战的全方位解析
java·开发语言·架构
匿者 衍2 小时前
POI读取 excel 嵌入式图片(支持wps 和 office)
java·excel