@leetcode 成长之路
LeetCode 刷题笔记 Day1
1.两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
实例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解法1:暴力搜素
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ret;
for(int i =0; i<nums.size();i++)
{
for(int j=i+1; j<nums.size();j++)
{
if(target - nums[i]==nums[j])
{
ret.push_back(i);
ret.push_back(j);
break;
}
}
}
return ret;
}
};
解析:
该方法虽然能够比较简单实现,但是存在问题:使用两个for循环,时间复杂度为O(n^2),空间复杂度为O(1)。
解法2:使用HashMap,加快搜索速度
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ret;
map<int,int> hmap;
for(int i =0; i < nums.size(); i++)
{
hmap[nums[i]]=i;
}
for(int i =0; i < nums.size(); i++)
{
int diff = target - nums[i];
map<int,int>::iterator temp = hmap.find(diff);
if(temp != hmap.end() && temp->second != i)
{
ret.push_back(i);
ret.push_back(temp->second);
break;
}
}
return ret;
}
};
解析:
该方法首先使用for循环,将值压入map。之后通过map,实现快速的遍历。时间复杂度为O(n)
问题:
1.c++ map 的搜索复杂度为?