twosum(new edition)
来源:互联网 发布:windows的uac 编辑:程序博客网 时间:2024/05/22 05:50
//最优方法 map查找法,map的查询时间复杂度为LogN
#include<iostream>
#include<vector>
#include<map>
#include<unordered_map>//unordered_map的映射表是不会对键进行排序的,是按照存进去的顺序放置的,但是map创建的映射表则是会对键值进行排序的。
using namespace std;
class solution{
public:
vector<int> twosum(vector<int>&num, int& target)
{
map<int, int> hash;
map<int, int>::const_iterator iter;
map<int, int>::const_iterator iterend;
vector<int> result;
for (int i = 0; i < int(num.size()); i++)
{
int numtofind = target - num[i];
iter = hash.find(numtofind);
iterend = hash.end();
if (hash.find(numtofind) != hash.end())//由键索引值,键存的是数组值,值存的是数组索引
{
result.push_back(hash[numtofind]);
result.push_back(i);
}
else
{
hash[num[i]] = i;
}
}
return result;
}
};
int main()
{
vector<int> nums = {3,4,1,2,3,1};
int target = 2;
solution s;
vector<int> result;
result=s.twosum(nums, target);
cout << result[0] << ' ' << result[1] << endl;
}
#include<iostream>
#include<vector>
#include<map>
#include<unordered_map>//unordered_map的映射表是不会对键进行排序的,是按照存进去的顺序放置的,但是map创建的映射表则是会对键值进行排序的。
using namespace std;
class solution{
public:
vector<int> twosum(vector<int>&num, int& target)
{
map<int, int> hash;
map<int, int>::const_iterator iter;
map<int, int>::const_iterator iterend;
vector<int> result;
for (int i = 0; i < int(num.size()); i++)
{
int numtofind = target - num[i];
iter = hash.find(numtofind);
iterend = hash.end();
if (hash.find(numtofind) != hash.end())//由键索引值,键存的是数组值,值存的是数组索引
{
result.push_back(hash[numtofind]);
result.push_back(i);
}
else
{
hash[num[i]] = i;
}
}
return result;
}
};
int main()
{
vector<int> nums = {3,4,1,2,3,1};
int target = 2;
solution s;
vector<int> result;
result=s.twosum(nums, target);
cout << result[0] << ' ' << result[1] << endl;
}
阅读全文
0 0
- twosum(new edition)
- twoSum
- TwoSum
- TwoSum
- TwoSum
- twoSum
- TwoSum
- TwoSum
- TwoSum
- TwoSum
- TwoSum
- twoSum
- TwoSum
- twoSum
- TwoSum
- TwoSum
- twosum
- TwoSum
- 火星人
- Kernighan-Lin算法
- a^b === c (mod p)知二求一: p已知
- Android实现点击通知栏后,先启动应用再打开目标Activity 144
- OC runtime知识
- twosum(new edition)
- 虚函数实现原理
- 自记linux命令
- java.lang.UnsatisfiedLinkError: dlopen failed: library "XXX.so" not found
- 续上面
- 我们做App的一定要用这种友好的方式去跟用户交互
- opencv 中常用的数据类型
- 快学numpy01
- 封装自己的jq插件