第10周作业1(LeetCode1)
来源:互联网 发布:smartgit linux 安装 编辑:程序博客网 时间:2024/06/10 14:54
1. 题目描述
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
2. 解决思路
这道题比较简单,解题思路也很容易想到,就是将数组排序以后利用数组头尾的元素相加与目标值作比较的结果,来动态移动头或者尾的下标,进而逐渐向数组中间靠拢。这样一来就只遍历了数组一遍,时间复杂度为O(n),而数组 排序的时间复杂度为O(nlogn),所以最后的时间复杂度为O(nlogn)。
3. 完整代码
#include<iostream>#include<vector>#include<algorithm>using namespace std;int main(){ vector<int> nums; int target = 0; int temp = 0; cout << "请输入整数nums的各元素(请用非int类型字符结束数组输入):" << endl; while(cin >> temp) { nums.push_back(temp); } sort(nums.begin(), nums.end()); cout << "请输入目标值:" << endl; cin >> target; for (int i = 0, j = nums.size() - 1; i <= j;) { if (nums[i] + nums[j] > target){ j--; } else if (nums[i] + nums[j] < target) { i++; }else { cout << "两元素之和等于目标值的索引是[" << i << "," << j << "]" << endl; break; } } return 0;}
阅读全文
0 0
- 第10周作业1(LeetCode1)
- leetcode1
- leetcode1
- leetcode1
- leetcode1
- Leetcode1
- 第10周作业(二)
- 第6周作业1
- 第3周作业1
- LeetCode1—10 JavaScript解法
- 第10周作业2(LeetCode2)
- 第1周作业-程序练手
- 第1周作业-程序练手
- 第7周作业1-循环大战
- 第7周作业1-循环大战
- 第7周作业1-循环大战
- 第7周作业1-循环大战
- 第7周作业1-循环大战
- 对log4j的简单封装
- iOS多线程编程——GCD与NSOperation总结
- 微信朋友圈,QQ空间,微博等列表展示的功能实现
- 常用插件--bootstrap3-dialog
- WPF不同线程之间的控件的访问
- 第10周作业1(LeetCode1)
- python3使用requests包抓取并保存网页源码
- Linux虚拟网络之tun(三)隔离网络下的Raw转发
- 452. Minimum Number of Arrows to Burst Balloons Java解法
- ImageLoader使用及源码解析
- RadioButton动态设置Margin
- java 如果文件目录不存在就创建再写文件的代码实例--针对“系统找不到指定的路径”问题。
- mybatis 在select语句中使用foreach语句报错
- 18 QT里的摄像头编程