【Two Sum】cpp
题目:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
代码:
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { std::vector<int> ret_vector; std::map<int,int> value_index; for (int i = 0; i < numbers.size(); ++i) { const int gap = target - numbers[i]; if (value_index.find(gap) != value_index.end()) { ret_vector.push_back(std::min(i+1,value_index[gap]+1)); ret_vector.push_back(std::max(i+1,value_index[gap]+1)); break; } else { value_index[numbers[i]] = i; } } return ret_vector; } };
Tips:
元素无序且要求复杂度O(n)的,就可以用hashmap解决。
网上有的算法先遍历一遍numbers获得所有元素的map<value,index>,再进行后续的计算。这样的算法没有考虑数组元素重复的case
比如:
numbers = [0,2,4,0]
target = 0
===========================================
第二次过此题,大体思路非常明确。额外开一个hashmap,访问数组一次就搞定。
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> ret; unordered_map<int, int> value_index; for ( int i=0; i<nums.size(); ++i ) { if ( value_index.find(target-nums[i])!=value_index.end() ) { ret.push_back(i+1); ret.push_back(value_index[target-nums[i]]+1); break; } value_index[nums[i]] = i; } std::sort(ret.begin(), ret.end()); return ret; } };
tips:
有三个细节需要注意:
1. [3, 2, 4] 6 对于这种类型的,一定要把value_index[nums[i]]=i放在if语句的后面,要不然同一个元素3就被用了两次
2. 题目要返回的index并不是数组下标,而是数组下标加1,且返回的值要求有序