您的位置:首页 > 其它

leetcode - Two Sum

2014-09-10 15:37 295 查看
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:
std::vector<int> twoSum(std::vector<int> &numbers, int target) {
#if 0
int index1 = 0, index2 = 0;
bool isFind = false;
std::sort(numbers.begin(),numbers.end());
for (int i = 0; i < numbers.size(); i++)
{
for (int j = i+1; j < numbers.size(); j++)
{
if(numbers[i] + numbers[j] == target)
{
index1 = i + 1;
index2 = j + 1;
isFind = true;
break;
}
}
if(isFind) break;
}
#if 0
std::cout << index1 << " " << index2 << std::endl;
#endif // 0

std::vector <int> vec;
vec.push_back(index1);
vec.push_back(index2);
return vec;
#endif // 一般解法,时间复杂度O(n^2),TLE code.
#if 1
std::vector<int> res;
std::map<int, int> mapInt;
for (int i = 0; i < numbers.size(); i++)
{
if(mapInt.find(target - numbers[i]) != mapInt.end())
{
res.push_back(mapInt.find(target - numbers[i])->second + 1);
res.push_back(i + 1);
}
else
{
mapInt.insert(std::pair<int, int>(numbers[i],i));
}
}
#if 1
std::cout << res[0] << " " << res[1] << std::endl;
#endif // 1

return res;
#endif // 使用map,将数据采用value - index方式存放到map当中,(value->数据的值,index数据的下标),然后,通过遍历数据,比如
// 查找当前的numbers[i]是否存在map当中,即map.find(target - numbers[i]),如果存在,找到结果,不存在,则将当前numbers[i]
// 存放到map当中。继续下一个数据的与当前map中的数据比较,最后找到符合条件的结果。
// 时间复杂度O(nlogn),这题已经AC.

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: