method 1 : O(n) map the value to index
http://www.geeksforgeeks.org/unordered_map-in-stl-and-its-applications/
unorder_map
method 2. This is best since it both reduce the timing and space complexity
https://web.stanford.edu/class/cs9/lectures/04/Two-Sum.pdf
sort and binary search
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector <int> result;
unordered_map<int, int> valMapToIndex;
for (int i = 0; i < nums.size(); ++i)
{
valMapToIndex[nums[i]] = i;
}
for (int i = 0; i < nums.size(); ++i)
{
if ((valMapToIndex[target - nums[i]] != 0) /*&& (valMapToIndex[target - nums[i]] != i+1)*/)
{
result.push_back(i);
result.push_back(valMapToIndex[target - nums[i]]);
// This "break" avoid the duplicated output
break;
}
}
return result;
}
};
method 3. O(n2)的方法
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
for (int i = 0; i < nums.size(); ++i)
{
for (int j = i+1; j< nums.size(); ++j)
{
if ((nums[i] + nums[j]) == target)
{
result.push_back(i);
result.push_back(j);
}
}
}
return result;
}
};