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()  结束
}
相关推荐
资生算法程序员_畅想家_剑魔6 分钟前
Java常见技术分享-设计模式的六大原则
java·开发语言·设计模式
dazzle10 分钟前
Python数据结构(五):队列详解
数据结构·python
爱编码的傅同学17 分钟前
【今日算法】LeetCode 25.k个一组翻转链表 和 43.字符串相乘
算法·leetcode·链表
Howrun77717 分钟前
C++ 智能指针_详细解释
开发语言
stolentime17 分钟前
P14978 [USACO26JAN1] Mooclear Reactor S题解
数据结构·c++·算法·扫描线·usaco
Cherry的跨界思维18 分钟前
【AI测试全栈:质量】40、数据平权之路:Python+Java+Vue全栈实战偏见检测与公平性测试
java·人工智能·python·机器学习·ai测试·ai全栈·ai测试全栈
刀法如飞19 分钟前
从零手搓一个类Spring框架,彻底搞懂Spring核心原理
java·设计模式·架构设计
老歌老听老掉牙21 分钟前
差分进化算法深度解码:Scipy高效全局优化实战秘籍
python·算法·scipy
编程大师哥23 分钟前
JavaScript DOM
开发语言·javascript·ecmascript
dazzle23 分钟前
Python数据结构(四):栈详解
开发语言·数据结构·python