0
点赞
收藏
分享

微信扫一扫

【电脑组装】✈️从配置拼装到安装系统组装自己的台式电脑

泠之屋 2024-09-19 阅读 19

大纲

题目

地址

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:

Example 2:

Example 3:

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

举报

相关推荐

0 条评论