class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{ /** 由于unorder_map速度要比map快所以选择无序哈希表 */
vector<int> res;
unordered_map<int, int> hash;
for(int i=0; i < nums.size();++i)
{
int another = target - nums[i];
if(hash.count(another))
{
res = vector<int>({hash[another], i});
return res;
}
hash[nums[i]] = i;
}
return res;
}
};
这两种写法的含义是不一样的:
if (hash.count(key))
是判断hash
表中是否存在关键字key
;if (hash[key])
是判断key
对应的value
值是否是真,如果key
在hash
表中不存在,则会先为其创建默认值,比如int
的默认值是0
,vector<int>
的默认值是vector<int>()
;
在C++中,如果想往哈希表中插入一对(key, value)
,一般写hash[key] = value
;
如果想查找一个key
是否存在,一般有两种写法:
if (hash.find(key) != hash.end())
if (hash.count(key) != 0)
第二种写法短一些,所以用得比较多。