当前位置:网站首页>LeetCode 35. 搜索插入位置 —vector遍历(O(logn)和O(n)的写法---二分查找法)
LeetCode 35. 搜索插入位置 —vector遍历(O(logn)和O(n)的写法---二分查找法)
2022-07-04 14:00:00 【Tianchao龙虾】
LeetCode 35. 搜索插入位置 —vector遍历(O(logn)和O(n)的写法—二分查找法)。
题目地址: https://leetcode.cn/problems/search-insert-position/
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
示例 1:
输入: nums = [1,3,5,6], target = 5
输出: 2
题目解法:
O(n)的写法:
一开始我的写法如下: 考虑整体遍历这个vector,然后看目标值是否小于等于这个当前值,是的话直接返回索引。
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if(nums.empty()) return 1;
const int size = nums.size();
for (size_t i=0; i<size; ++i){
if (target <= nums[i]) return i;
}
return size;
}
};
但是看了题解之后,有如下写法:
O(logn)的写法:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if(nums.empty()) return 1;
const int size = nums.size();
int left=0, right=size-1;
while(left<=right){
auto middle = left+(right-left)/2;
if(nums[middle] <target)
left = middle+1;
else
right = middle -1;
}
return left;
}
};
题目笔记
最上面的当然是可以得到结果,但是下面的优势在于,使用了二分查找的思想。但前提是这个数组是有序的。 前面当然是比较直观的,但是复杂度在O(n),二分查找只需要O(logn)。
边栏推荐
猜你喜欢

Korean AI team plagiarizes shock academia! One tutor with 51 students, or plagiarism recidivist

都在说DevOps,你真正了解它吗?

力扣刷题01(反转链表+滑动窗口+LRU缓存机制)

智能客服赛道:网易七鱼、微洱科技打法迥异

03 storage system

SAIC Maxus officially released its new brand "mifa", and its flagship product mifa 9 was officially unveiled!

5G电视难成竞争优势,视频资源成中国广电最后武器

LVGL 8.2 text shadow

03-存储系统

5g TV cannot become a competitive advantage, and video resources become the last weapon of China's Radio and television
随机推荐
【学习笔记】拟阵
Is BigDecimal safe to calculate the amount? Look at these five pits~~
Decimal, exponential
Five minutes of machine learning every day: how to use matrix to represent the sample data of multiple characteristic variables?
Ranking list of databases in July: mongodb and Oracle scores fell the most
Introduction to asynchronous task capability of function calculation - task trigger de duplication
现代控制理论入门+理解
C language course design questions
深度学习 神经网络的优化方法
ES6 modularization
Redis publier et s'abonner
Summer Review, we must avoid stepping on these holes!
Leetcode 1200 minimum absolute difference [sort] The Path of leetcode for heroding
Summary of common problems in development
Dialogue with ye Yanxiu, senior consultant of Longzhi and atlassian certification expert: where should Chinese users go when atlassian products enter the post server era?
hexadecimal
Deep learning neural network case (handwritten digit recognition)
Luo Gu - some interesting questions
Is it safe to open an account online for stock speculation? Will you be cheated.
LVGL 8.2 LED