当前位置: 首页 > news >正文

闯关leetcode——35. Search Insert Position

大纲

  • 题目
    • 地址
    • 内容
  • 解题
    • 代码地址

题目

地址

https://leetcode.com/problems/search-insert-position/description/

内容

Given a sorted array of distinct integers 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 must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [1,3,5,6], target = 5
Output: 2

Example 2:

Input: nums = [1,3,5,6], target = 2
Output: 1

Example 3:

Input: nums = [1,3,5,6], target = 7
Output: 4

Constraints:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums contains distinct values sorted in ascending order.
  • -104 <= target <= 104

解题

这题要求在一个无重复的、升序数组中,寻找一个数的下标。如果该数不存在,则寻找到可以插入该数的下标。
这个算是二分查找问题的一个变种。一般情况下,我们要求二分查找算法在数据不存在的情况下,返回-1,表示没有找到。如果我们希望返回可以插入数据的位置,只需要对返回-1的地方做个修改,让其返回待插入的位置。

#include <vector>
using namespace std;class Solution {
public:int searchInsert(vector<int>& nums, int target) {int right = nums.size() - 1;return binarySearch(nums, target, 0, right);}
private:int binarySearch(const vector<int>& nums, int target, int left, int right) {if (left > right) {return left;}int mid = (left + right) / 2;if (nums[mid] == target) {return mid;} else if (nums[mid] < target) {return binarySearch(nums, target, mid + 1, right);} else {return binarySearch(nums, target, left, mid - 1);}}
};

在这里插入图片描述

代码地址

https://github.com/f304646673/leetcode/tree/main/35-Search-Insert-Position


http://www.mrgr.cn/news/29861.html

相关文章:

  • windows C++ 并行编程-异步消息块(一)
  • Linux驱动开发 ——架构体系
  • JDBC编程详细总结
  • 「C++系列」异常处理
  • 速盾:凡科建站开cdn了吗?
  • 【从计算机的发展角度理解编程语言】C、CPP、Java、Python,是偶然还是应时代的产物?
  • 硬件开篇——体系架构
  • 408算法题leetcode--第八天
  • [Redis][Redis简介]详细讲解
  • 【无标题】Java_Se 数据变量与运算符
  • Linux C高级 day1
  • 7.7opencv中(基于C++) 翻转图像
  • Linux运维篇-服务器简介
  • 微博计算架构实战
  • Linux进阶 查看系统进程
  • 【漏洞复现】Nacos Derby SQL注入漏洞
  • Java中的语法糖:让编程更简洁的特性
  • 15. 三数之和(左右指针)
  • 【protobuf】ProtoBuf的学习与使用⸺C++
  • Springboot多种请求参数