搜索插入位置
来源:互联网 发布:淘宝图片什么格式 编辑:程序博客网 时间:2024/06/07 02:33
描述
给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
你可以假设在数组中无重复元素
样例
[1,3,5,6],5 → 2
[1,3,5,6],2 → 1
[1,3,5,6],7 → 4
[1,3,5,6],0 → 0
思考
- 如果数组中存在元素i , 使得 A[i] >= target , 则返回元素索引
- 如果不存在此元素,说明target > A[i], 返回 A.size()
代码
// By Lentitudeclass Solution { /** * param A : an integer sorted array * param target : an integer to be inserted * return : an integer */public: int searchInsert(vector<int> &A, int target) { // write your code here if (A.empty()){ return 0; } //因不清楚原数组是升序,降序,所以先进行升序处理 sort(A.begin(), A.end()); for (int i = 0; i != A.size(); ++i){ //如果在数组中找到目标值则返回索引.如果没有, 返回到它将会被按顺序插入的位置 if (A[i] >= target){ return i; } } //说明 target > A[A.size() - 1] return A.size(); }};
0 0
- 题目:搜索插入位置
- LintCode : 搜索插入位置
- 搜索插入位置
- 搜索插入位置
- 搜索插入位置
- lintcode ----搜索插入位置
- LintCode : 插入搜索位置
- 搜索插入位置
- Lintcode 搜索插入位置
- 搜索插入位置
- 搜索插入位置
- 搜索插入位置
- lintcode:搜索插入位置
- Lintcode搜索插入位置
- lintCode 搜索插入位置
- LintCode_060_搜索插入位置
- 60. 搜索插入位置
- 【lintcode笔记】搜索插入位置
- Domain models and metadata(领域模型和元数据)
- Jmeter基础-集合点
- 5基础构建模块——并发容器
- 3sum leetcode
- Excel Sheet Column Number
- 搜索插入位置
- gangliaWeb汉化及优化(二)--连接hadoop
- Retrofit的讲解和使用
- 实现字符串类型的深拷贝
- 小白自学之路---html常用标签
- JNI/NDK开发指南(二)
- leetcode 122. Best Time to Buy and Sell Stock II
- 2017华为精英挑战赛总结
- div高度自适应