题目:Two Sum
代码:
//
// Created by HINTS on 2019/2/20.
//
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
//1.使用hashmap,以空间换时间
/*
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> m;
vector<int> res;
for (int i = 0; i < nums.size(); ++i) {
m[nums[i]] = i;
}
for (int i = 0; i < nums.size(); ++i) {
int t = target - nums[i];
if(m.count(t) && m[t] != i){
res.push_back(m[t]);
res.push_back(i);
break;
}
}
return res;
}
*/
//2.暴力破解
/*
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
for (int i = 0; i < nums.size(); ++i) {
for (int j = i + 1; j < nums.size(); ++j) {
if (target == nums[i] + nums[j]){
res.push_back(i);
res.push_back(j);
}
}
}
return res;
}
*/
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); ++i) {
int t = target - nums[i];
if(m.count(t)){
return {i, m[t]};
}
m[nums[i]] = i;
}
return {};
}
int main(){
vector<int > nums = {2, 7, 11, 5};
int target = 9;
vector<int > res = twoSum(nums, target);
for (int i = 0; i < res.size(); ++i) {
cout << res[i] << endl;
}
return 0;
}
总结:
暴力破解会超出时间限制 使用hashmap,异空间换时间,hashmap时间复杂度为O(1)