
两数之和
发布日期:2021-05-27 01:30:47
浏览次数:5
分类:技术文章
本文共 1636 字,大约阅读时间需要 5 分钟。
#include<iostream>
#include <vector> using namespace std;class Solution {
public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> m; vector<int> a; int flag = 0; for (int i = 0; i < nums.size(); ++i) { if (m.count(target - nums[i])) { return {i, m[target - nums[i]]}; } m[nums[i]] = i; } return {}; } };void trimLeftTrailingSpaces(string &input) {
input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) { return !isspace(ch); })); }void trimRightTrailingSpaces(string &input) {
input.erase(find_if(input.rbegin(), input.rend(), [](int ch) { return !isspace(ch); }).base(), input.end()); }vector<int> stringToIntegerVector(string input) {
vector<int> output; trimLeftTrailingSpaces(input); trimRightTrailingSpaces(input); input = input.substr(1, input.length() - 2); stringstream ss; ss.str(input); string item; char delim = ','; while (getline(ss, item, delim)) { output.push_back(stoi(item)); } return output; }int stringToInteger(string input) {
return stoi(input); }string integerVectorToString(vector<int> list, int length = -1) {
if (length == -1) { length = list.size(); }if (length == 0) {
return "[]"; }string result;
for(int index = 0; index < length; index++) { int number = list[index]; result += to_string(number) + ", "; } return "[" + result.substr(0, result.length() - 2) + "]"; }int main() {
string line; while (getline(cin, line)) { vector<int> nums = stringToIntegerVector(line); getline(cin, line); int target = stringToInteger(line); vector<int> ret = Solution().twoSum(nums, target);string out = integerVectorToString(ret);
cout << out << endl; } return 0; }转载地址:https://blog.csdn.net/huohunri2013/article/details/86481000 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
能坚持,总会有不一样的收获!
[***.219.124.196]2023年11月07日 01时30分12秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
N1文法「第1-第5」
2019-03-25
【日语】【歌词】「ヤキモチ」--高橋優
2019-03-25
[SRv6]《SRv6网络编程》SRv6网络在电信云中的应用
2019-03-25
[SRv6]《SRv6网络编程》SRv6网络在SD-WAN中的应用
2019-03-25
[SRv6]《SRv6网络编程》SRv6 OAM与随路网络测量(1/2:OAM)
2019-03-25
[转载] 最深的云网融合:多接入边缘计算(MEC)
2019-03-25
[SRv6]《SRv6网络编程》SRv6 OAM与随路网络测量(2/2:IFIT)
2019-03-25
【日语】【歌词】「Lemon」--米津玄师
2019-03-25
[5GC]《5G核心网-赋能数字化时代》| 6.3用户面处理
2019-03-25
Clion安装配置(Windows)
2019-03-25
C++中vector使用find函数查找struct结构体内容
2019-03-25
C++11产生随机数
2019-03-25
C++如何提高Vector效率的一些方法
2019-03-25
【快手笔试T1】数组优先级排序
2019-03-25
整数取反(取负)运算
2019-03-25
关于C++内置排序函数sort的自定义比较器cmp用法
2019-03-25
【头条笔试T2】
2019-03-25
使用hexo搭建博客,文件无法加载的问题
2019-03-25
Socket Server指定监听端口和IP
2019-03-25
Ubuntu网络连接图标消失
2019-03-25