# 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].
# Solution
Approach 1: Brute force.
Approach 2: Hash table.
Approach 3: Sort then use two pointers.
# Code (Python)
Approach 3:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
sorted_nums = sorted((num, i) for i, num in enumerate(nums))
l, r = 0, len(sorted_nums) - 1
while l < r:
if sorted_nums[l][0] + sorted_nums[r][0] == target:
return [sorted_nums[l][1], sorted_nums[r][1]]
elif sorted_nums[l][0] + sorted_nums[r][0] < target:
l += 1
else:
r -= 1
# Code (C++)
Approach 1:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
int n = nums.size();
if (n <= 1)
{
return res;
}
for (int i = 0; i < n - 1; ++i)
{
for (int j = i + 1; j < n; ++j)
{
if (nums[i] + nums[j] == target)
{
res.push_back(i);
res.push_back(j);
}
}
}
return res;
}
};
Approach 2:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> res;
int n = nums.size();
if (n <= 1)
{
return res;
}
unordered_map<int,int> umap;
for (int i = 0; i < n; ++i)
{
int tmp = target - nums[i];
if (umap.find(tmp) != umap.end())
{
res.push_back(i);
res.push_back(umap[tmp]);
break;
}
umap[nums[i]] = i;
}
return res;
}
};