35. 搜索插入位置

本文介绍了一个简单的二分查找算法实现,用于在一个已排序的数组中查找目标值的位置,若未找到则返回插入位置。通过几个示例展示了算法的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、题意
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:

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

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

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

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

二、分析和解答

 public int searchInsert(int[] nums, int target) {
        int low = 0,high = nums.length - 1;
        while(low <= high){
            int mid = (low + high) / 2;
            if(nums[mid] == target){
                return mid;
            }else if(nums[mid] > target){
                high = mid - 1;
            }else
                low = mid + 1;
        }        
            return low;
    }

一个简单的二分查找!
1、如果while中的条件是low < high 的时候,只存在两种指针的形式:
(1)low和high指向同一位置;
(2)low在high指针的右边;
假设此时数组中不存在target的值:如果target和数组的两边缘有关系(即target在数组边界元素的前面或者后面),那么此时low和high指针都会指向边界元素,否则low 在high指针的右边。
以数组[1,3,5,6]为例:
(1)当target为0时,low和high指向数组的第一个元素,即下标0,(target < nums[0])返回low;
(2)当target为2时,low和high指向数组的第一个元素,即下标0,(target > nums[0])返回low + 1;
(3)当target为7时,low和high指向数组的最后一个元素,即下标3,(target > nums[3])返回low+1;
(4)当target为4时,low指针指向位置2,同时high指向位置1,(target < nums[2])返回low;

2、如果while中的条件是low <= high 的时候,只存在一种指针的形式:low在high指针的右边;
(1)如果是在左边界上,high肯定是-1(越界),low为位置0;如果在右边界上,low肯定是nums.length(越界),high为最后一个位置!
(2)和边界没关系,low在high的右边,但都不越界。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值