目录
Google:
Given a list of numbers and a number k, return whether any two numbers from the list add up to k
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
这是谷歌很经典的一道题,在数组中寻找两个数,它们的和是否为k.
基本上所有的算法题,都有一个暴力解。我们就先从暴力解法开始。
注意:笔者会尽量使用新的C++语法来描述算法,而不是类C的代码风格。
Solution 1 暴力法:
#include <iostream>
#include <vector>
#include <algorithm>
bool TwoSum(std::vector<int> data, int k)
{
int index = 1;
auto iterFind = std::find_if(data.begin(), data.end(), [=, &index](int val){
int leftSum = k - val;
auto iter = std::find(data.begin() + index, data.end(), leftSum);
index ++;
if(iter != data.end())
{
return true;