博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
35. Search Insert Position
阅读量:4518 次
发布时间:2019-06-08

本文共 1138 字,大约阅读时间需要 3 分钟。

Given a sorted array 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 may assume no duplicates in the array.-----------------------Input: [1,3,5,6], 5Output: 2-----------------------Input: [1,3,5,6], 2Output: 1-----------------------Input: [1,3,5,6], 7Output: 4-----------------------Input: [1,3,5,6], 0Output: 0

 ------------------------------------------------------------------------------------------------------------------------

返回target在有序数组中的位置。如果没有找到,就返回这个数应该放在的位置:

 代码如下:

int searchInsert(vector
& nums, int target) { if(nums.capacity() == 0) return 0; if(target > nums[nums.capacity() - 1]) //如果要找的数比最后一个数还要大,它的位置应该在末尾 return nums.capacity(); for(int i = 0; i < nums.capacity(); i++){ if(nums[i] >= target) //找到这个数,或者把它放在第一个比它大的数的位置 return i; } }

 

转载于:https://www.cnblogs.com/hozhangel/p/7846209.html

你可能感兴趣的文章
python3 爬取百合网的女人们和男人们
查看>>
kubernetes源码阅读笔记——Kubelet(之三)
查看>>
如何利用jQuery post传递含特殊字符的数据
查看>>
中国剩余定理
查看>>
Codeforces 543.B Destroying Roads
查看>>
noip模拟赛 寻宝之后
查看>>
洛谷P1461 海明码 Hamming Codes
查看>>
ZOJ2833*(并查集)
查看>>
外连接简要总结
查看>>
第一次作业-准备篇
查看>>
【C++】继承时构造函数和析构函数
查看>>
shader一些语义或术语的解释
查看>>
opencv源代码之中的一个:cvboost.cpp
查看>>
Android通过泛型简化findViewById类型转换
查看>>
swift
查看>>
eclipse maven 插件的安装和配置
查看>>
mysql基本知识总结
查看>>
php的zend引擎执行过程 一
查看>>
pycharm 快捷键
查看>>
Linux常用命令
查看>>