[leetcode刷题 C++] 1. Two Sum
-
题目
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, and you may not use the same element twice.Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
-
思路
-
O(n^2) 遍历每个元素x,查看在给定的数组中是否有数值等于target-x
最开始想到的就是这个方法。代码如下:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int>::iterator it; vector<int> dummy; for(it = nums.begin(); it != nums.end(); it++) { for(auto jt = it+1; jt != nums.end(); jt++) { if(*it + *jt == target) { return vector<int>{it - nums.begin(), jt - nums.begin()} } } } return dummy; } };
-
O(n) 使用hash表省去寻找(target - x)的时间
要将时间复杂度从O(n^2)降低到O(n),就需要减少寻找(target - x)的时间,即从数组中查找某一个元素的时间,那么很自然的就想到了hash表,查找的平均复杂度为O(1)。所以在使用hash表后,整体的时间复杂度可以为O(n)。
其中,unordered_map是使用hash表实现的:https://blog.csdn.net/hk2291976/article/details/51037095代码如下:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> hash_tbl; vector<int>::iterator it; unordered_map<int, int>::const_iterator found_it; vector<int> dummy; for(it = nums.begin(); it != nums.end(); it++) { found_it = hash_tbl.find(target - *it); if(found_it != hash_tbl.end()) { return vector<int>{found_it->second, it - nums.begin()}; } else { hash_tbl.insert({*it, it-nums.begin()}); } } return dummy; } };