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

二.搜索插入位置

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 解法一

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 解法二

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()  结束
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蔚一

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值