第12周作业1(LeetCode35)
来源:互联网 发布:腾讯国际足球数据库 编辑:程序博客网 时间:2024/06/16 02:31
1. 题目描述
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.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
2. 解决思路
解决这道题首先容易想到顺序遍历数组,因为数组已经是排好序的,所以只要依次比较找到第一个不小于target值的数组元素即可得到target的插入(所在)的位置,这样一来的时间复杂度为O(n),其中n为数组元素的个数(数组长度)。
很显然,这不是最有效的解决办法,进而我们就想到了利用二分查找来解决,这样的时间复杂度降低为O(logn),其他细节可见代码注释。
3. 完整代码
#include<iostream>#include<algorithm>#include<vector>using namespace std;int BinarySearchInsert(vector<int> &array , int key){ if (array.back() < key) return array.size(); int begin = 0; int end = array.size() - 1; while (begin < end) { int mid = begin + (end - begin) / 2;//避免begin+end的结果溢出 if (array[mid] > key) { end = mid; } else if (array[mid] < key) { begin = mid + 1; } else { return mid; } } return end;}int main(){ vector<int> arr; int target = 0; int temp = 0; cout << "请按从小到大的顺序输入数组arr的各元素:" << endl; while (cin >>temp ) { arr.push_back(temp);//注意此行代码与下面if判断的顺序不能调换,否则最后一个temp将不会保存进array if (cin.peek() == '\n') { break; } } cout << "请输入目标值:" << endl; cin >> target; int result = BinarySearchInsert(arr,target); cout << "目标所在或应插入的位置是:\n" << result << endl; return 0;}
阅读全文
0 0
- 第12周作业1(LeetCode35)
- JAVA第12周作业1
- 第12周作业三
- [leetcode]第12周作业
- 第6周作业1
- 第3周作业1
- 第12周作业(第八章)
- 第12周作业2(LeetCoed26)
- 第1周作业-程序练手
- 第1周作业-程序练手
- 第7周作业1-循环大战
- 第7周作业1-循环大战
- 第7周作业1-循环大战
- 第7周作业1-循环大战
- 第7周作业1-循环大战
- 第7周作业1-循环大战
- 第7周作业1-循环大战
- 第7周作业1-循环大战
- Apach Zeppelin和Apach Livy搭配使用配置
- MySQL数据库(29)
- article, aside,nav(导航),section,time 元素和 pubdate 属性,pudate元素
- 前端需求中有一类名叫活动
- “Word文件设置了多级列表,却还是不能创建目录”的解决办法
- 第12周作业1(LeetCode35)
- 基于spring的web项目中一些配置文件的解释
- [开源发布]SVN资源权限管理系统-安全流畅极简可靠
- 数组分割
- eclipse中maven项目jar包不会自动下载解决办法
- 2017.5.14测试 第2题: 魔法阵
- selenium使用chrome浏览器
- tensorflow中的关键字global_step使用
- JavaScript拖拽(四):面向对象和继承