leetcode 1 两数之和
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> record(2,0);
for(int i =0;i<nums.size();i++)
{
int comparenum1 = nums[i];
for(int j=i+1;j<nums.size();j++)
{
int comparenum2 = nums[j];
if(target == comparenum1 +comparenum2)
{
record[0]=i;
record[1]=j;
}
}
}
return record;
}
};
考虑到时间复杂度,查看leetcode题解,使用到了
map哈希,时间复杂度由O(n^2)降到了O(n)
#include <vector>
using namespace std;
class Solution
{
public:
vector<int> twoSum(vector<int> &nums,int target)
{
unordered_map<int,int> record;
for(int i = 0;i<nums.size();i++)
{
int complement = target -nums[i];
if(record.find(complement) != record.end())
{
int res[] = {i,record[complement]};
return vector<int>(res,res+2);
}
record[nums[i]]=i;
}
}
};