35、搜索插入位置

  1. 35、搜索插入位置
    1. 示例 1:
    2. 示例 2:
    3. 示例 3:
    4. 示例 4:
  • 题解
    1. 1、二分查找
  • 35、搜索插入位置

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

    你可以假设数组中无重复元素

    示例 1:

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

    示例 2:

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

    示例 3:

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

    示例 4:

    输入: [1,3,5,6], 0
    输出: 0
    

    链接:https://leetcode-cn.com/problems/search-insert-position

    题解

    1、二分查找

    class Solution {
        public int searchInsert(int[] nums, int target) {
            int exist = -1;
            int l = 0;
            int r = nums.length - 1;
            // 二分查找
            while (l <= r) {
                int mid = (l + r + 1) >> 1;
                if (nums[mid] == target) {
                    exist = mid;
                    break;
                } else if (nums[mid] > target) {
                    r = mid - 1;
                } else {
                    l = mid + 1;
                }
            }
            // 找到
            if (exist != -1) {
                return exist;
            } else { // 没找到
                // 返回需要被插入的位置
                if (l < nums.length - 1 && nums[l] <= target) return l+1;
                else return l;
            }
        }
    }
    

    转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1056615746@qq.com

    💰

    Title:35、搜索插入位置

    Count:255

    Author:攀登

    Created At:2020-07-26, 00:19:44

    Updated At:2024-06-15, 15:52:32

    Url:http://jiafeimao-gjf.github.io/2020/07/26/35%E3%80%81%E6%90%9C%E7%B4%A2%E6%8F%92%E5%85%A5%E4%BD%8D%E7%BD%AE/

    Copyright: 'Attribution-non-commercial-shared in the same way 4.0' Reprint please keep the original link and author.

    ×

    Help us with donation