# LeetCode Two Sum

LeetCode Two Sum
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>& nums, int target) {
vector<int> nums_copy = nums;
sort(nums_copy.begin(), nums_copy.end());
int i = 0, j = nums_copy.size() - 1;
while (i != j)
{
if (nums_copy[i] + nums_copy[j] == target)
break;
else if (nums_copy[i] + nums_copy[j] < target)
i++;
else
j--;
}
vector<int> ans(2);
for (int k = 0; k < nums.size(); k++)
{
if (ans[0] == 0 && nums[k] == nums_copy[i])
ans[0] = k + 1;
else if (ans[1] == 0 && nums[k] == nums_copy[j])
ans[1] = k + 1;
}
if (ans[0] > ans[1])
swap(ans[0], ans[1]);
return ans;
}
};

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//map<int, int> nums_index;
unordered_map<int, int> nums_index; // unordered_map比map快
vector<int> ans(2);
for (int i = 0; i < nums.size(); i++)
{
int added = target - nums[i];