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比较。其代价过大,代码为:

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         vector<int> result;
 5         unordered_map<int,int> hash;
 6         for(int i = 0; i < nums.size(); i++)
 7         {
 8             int num_to_find = target - nums[i];
 9             if(hash.find(num_to_find) != hash.end())
10             {
11                 result.push_back(hash[num_to_find]);
12                 result.push_back(i);
13                 return result;
14             }
15             else
16             {
17                 hash[nums[i]] = i;
18             }
19         }
20         return result;
21     }
22 };

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

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         vector<int> result;
 5         unordered_map<int,int> hash;
 6         for(int i = 0; i < nums.size(); i++)
 7         {
 8             int num_to_find = target - nums[i];
 9             if(hash.find(num_to_find) != hash.end())
10             {
11                 result.push_back(hash[num_to_find]);
12                 result.push_back(i);
13                 return result;
14             }
15             else
16             {
17                 hash[nums[i]] = i;
18             }
19         }
20         return result;
21     }
22 };

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

 

posted @ 2016-12-28 11:58  yrwang  阅读(86)  评论(0编辑  收藏  举报