LeetCode 1. Two Sum

Problem: Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

该题最容易想到的暴力解法就是两层循环,逐对相加与target比较。其代价过大,代码为:

 class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
unordered_map<int,int> hash;
for(int i = ; i < nums.size(); i++)
{
int num_to_find = target - nums[i];
if(hash.find(num_to_find) != hash.end())
{
result.push_back(hash[num_to_find]);
result.push_back(i);
return result;
}
else
{
hash[nums[i]] = i;
}
}
return result;
}
};

时间复杂度为O(n)的做法是只遍历一次vector,然后用hash表的find快速查找存储的数字。其代码如下:

 class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
unordered_map<int,int> hash;
for(int i = ; i < nums.size(); i++)
{
int num_to_find = target - nums[i];
if(hash.find(num_to_find) != hash.end())
{
result.push_back(hash[num_to_find]);
result.push_back(i);
return result;
}
else
{
hash[nums[i]] = i;
}
}
return result;
}
};

已遇到多题巧用hash table(unordered_map)简化算法的方法,注意hash table的使用!

上一篇:RobotFramework中加载自定义python包中的library(一个py文件中有多个类)


下一篇:Android Drawable的9种子类 介绍