【c++&leetcode】35. Search Insert Position

问题入口

二分搜索

时间复杂度O(logn)

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int start = 0;
        int end = nums.size() - 1;

        while (start <= end)
        {
            int mid = (start + end) / 2;
            if (nums[mid] == target)
            {
                return mid;
            }
            else if(nums[mid] > target)
            {
                end = mid - 1;
            }
            else if(nums[mid] < target)
            {
                start = mid + 1;
            }
            
        }
        
        return start;
    }
};

由于给到的数组是从小到大的,可以使用二分搜索法,即以中间的元素为界,如果大于中间元素,范围限定在右半边,如果小于中间元素,范围限定在左半边。假设数组元素数为n,范围依次是n\rightarrow \frac{n}{2}\rightarrow \frac{n}{4}\rightarrow ...\rightarrow 1。假设通过k次找到指定元素, \frac{n}{2^{k}} = 1, k=log_{2}n。时间复杂度为O(logn)

时间复杂度O(n)

class Solution {
public:
    //O(n)
    int searchInsert(vector<int>& nums, int target) {
        for (int i = 0; i < nums.size(); i++)
        {
            if (nums[i] == target)
                return i;
            else
            {
                if (nums[i] > target)
                    return i;
                else
                    continue;
                
            }
        }
        return nums.size();
    }
};

相关推荐

  1. Day<span style='color:red;'>35</span>

    Day35

    2024-05-04 10:00:02      24 阅读
  2. 安卓UI面试题 31-35

    2024-05-04 10:00:02       39 阅读
  3. IOS面试题编程机制 31-35

    2024-05-04 10:00:02       35 阅读
  4. 力扣704/35/34:二分查找

    2024-05-04 10:00:02       37 阅读
  5. 题解:力扣704/35/34

    2024-05-04 10:00:02       33 阅读
  6. Redis面试题35

    2024-05-04 10:00:02       53 阅读
  7. Redis面试题35

    2024-05-04 10:00:02       61 阅读
  8. day35_js

    2024-05-04 10:00:02       56 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-04 10:00:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-04 10:00:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-05-04 10:00:02       87 阅读
  4. Python语言-面向对象

    2024-05-04 10:00:02       96 阅读

热门阅读

  1. R Business Problem

    2024-05-04 10:00:02       25 阅读
  2. 计算机网络 3.1网络的拓扑结构

    2024-05-04 10:00:02       31 阅读
  3. 计算机网络期末试题

    2024-05-04 10:00:02       33 阅读
  4. 【LeetCode】树的DFS(前序、中序、后序)精选10题

    2024-05-04 10:00:02       32 阅读
  5. 富格林:累积经验阻挠黑幕之手

    2024-05-04 10:00:02       29 阅读
  6. Django Admin报错“外键冲突”排查

    2024-05-04 10:00:02       28 阅读
  7. 你用过最好用的AI工具有哪些?

    2024-05-04 10:00:02       32 阅读
  8. 力扣经典150题第五十二题:简化路径

    2024-05-04 10:00:02       34 阅读