很简单。没什么好说的。但是在阿里实习的第四面的时候居然问到了。

大意是给出一组无序数列和目标数Z,在无序数列中找到X和Y,使得X+Y=Z。

有两种方法:

  一种是排序后,同时首尾搜索。时间复杂度为O(nlgn) + O(n) = O(nlgn)。空间复杂度为O(1)

  另一种是把公式转换为X = Z-Y. 从数列从头搜到尾,每个数假设为Y,因此可以得到X,找到X是否在序列中。时间复杂度为O(n),空间复杂度为O(n)

主要学习了STL的find_if、binary_search、和sort函数。更详细的可以看这篇博客


find_if函数原型为:

template <class InputIterator, class UnaryPredicate>
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);

实现等价于:

template<class InputIterator, class UnaryPredicate>
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred)
{
while (first!=last) {
if (pred(*first)) return first;
++first;
}
return last;
}

第三个参数pred是个函数指针或者函数对象,它的返回值应当可转化为bool类型,参数只有一个且应当声明为const。

find_if函数的返回值为(1)如果找到了,返回指向它的迭代器,(2)否则,返回last。


binary_search函数的原型为:

template <class ForwardIterator, class T>
bool binary_search (ForwardIterator first, ForwardIterator last,
const T& val);
template <class ForwardIterator, class T, class Compare>
bool binary_search (ForwardIterator first, ForwardIterator last,
const T& val, Compare comp);

实现等价于:

template <class ForwardIterator, class T>
bool binary_search (ForwardIterator first, ForwardIterator last, const T& val)
{
first = std::lower_bound(first,last,val);
return (first!=last && !(val<*first));
}

binary_search函数的第三个参数为要查找的目标值。第四个参数为函数指针或者函数对象。它需要两个参数,返回一个bool型。

对于第一个版本,只有三个参数,使用operator < 函数来进行比较。第二个版本有四个参数,用第四个参数进行比较。

对于第一个版本,如果!(a < b) && !(b < a)那么a就与b相等。第二个版本类似,(!comp(a, b) && !comp(b, a)), 那么a与b相等。

与find_if函数区别之一是: binary_search返回的是bool型而不是迭代器。所以binary_search函数只知道是否有这个值而无法得到准确的位置

        区别之二是:binary_search使用之前需要先排序。

如果迭代器不是random-access的也没关系,因为内部使用的是advance函数,只是这样复杂度就是o(n)了


sort函数原型

template <class RandomAccessIterator>
void sort (RandomAccessIterator first, RandomAccessIterator last);
template <class RandomAccessIterator, class Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

第三个参数是函数指针或者函数对象。
返回值是bool型,如果为真,表示a和b的偏序关系正确,为假表示不正确,需要交换。

完整代码如下:

class Solution {

struct MyStruct {
int data;
int original_pos;
}; struct MyPred {
MyPred(int d): data(d){}
int data;
bool operator() (MyStruct& tmp) {
return tmp.data == data;
}
}; public:
vector<int> twoSum(vector<int> &numbers, int target);
static bool myCmp(const MyStruct &a, const MyStruct &b) {
return a.data < b.data;
}
private: }; vector<int> Solution::twoSum(vector<int> &numbers, int target) {
vector<MyStruct>::iterator it;
vector<MyStruct>::iterator pos;
vector<MyStruct> myStructVec;
MyPred myPred(target); int index = ;
for (vector<int>::iterator it = numbers.begin(); it != numbers.end(); it++, ++index) {
MyStruct tmp;
tmp.data = *it;
tmp.original_pos = index;
myStructVec.push_back(tmp);
}
sort(myStructVec.begin(), myStructVec.end(), myCmp); for (it = myStructVec.begin(); it != myStructVec.end(); it ++) {
myPred.data = target - it->data;
if (myPred.data < it->data) {
it = myStructVec.end();
break;
}
if ((pos = find_if(it + , myStructVec.end(), myPred)) != myStructVec.end())
break;
} vector<int> ans;
if (it != myStructVec.end()) {
if (it->original_pos > pos->original_pos)
swap(it, pos);
ans.push_back(it->original_pos);
ans.push_back(pos->original_pos);
} return ans;
}

problem 1 -- Two sum的更多相关文章

  1. (Problem 6)Sum square difference

    Hence the difference between the sum of the squares of the first ten natural numbers and the square ...

  2. [LeetCode&Python] Problem 167. Two Sum II - Input array is sorted

    Given an array of integers that is already sorted in ascending order, find two numbers such that the ...

  3. [LeetCode&Python] Problem 653. Two Sum IV - Input is a BST

    Given a Binary Search Tree and a target number, return true if there exist two elements in the BST s ...

  4. [LeetCode&Python] Problem 1: Two Sum

    Problem Description: Given an array of integers, return indices of the two numbers such that they ad ...

  5. Project Euler Problem 18-Maximum path sum I & 67-Maximum path sum II

    基础的动态规划...数塔取数问题. 状态转移方程: dp[i][j] = num[i][j] + max(dp[i+1][j],dp[i+1][j+1]);

  6. Project Euler Problem 16-Power digit sum

    直接python搞过.没啥好办法.看了下别人做的,多数也是大数乘法搞过. 如果用大数做的话,c++写的话,fft优化大数乘法,然后快速幂一下就好了.

  7. UVa 108 - Maximum Sum(最大连续子序列)

    题目来源:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&pa ...

  8. poj 1564 Sum It Up

    题目连接 http://poj.org/problem?id=1564 Sum It Up Description Given a specified total t and a list of n ...

  9. 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)

    转自  http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...

随机推荐

  1. 问题-[Delphi]在对GRID设置单击为编辑时,其他GRID可以,但有一个GRID不行?

    问题现象:在对GRID设置单击为编辑时,其他GRID可以,但有一个GRID不行?问题原因:在这个GRID中的单击事件可能不存在,可以测试一下有没有单击事件.解决方法:需要在GRID的上一个类中,放开单 ...

  2. oc学习之路----代理模式

    今天刚学完oc的代理模式,觉得有点新奇,第一次接触,原理 A完成一件事,但是自己不能完成,于是他找个代理人B 替他完成这个事情,他们之间便有个协议 (protocol),B继承该协议来完成A代理给他的 ...

  3. Delphi- 调用存储过程的方法

    Delphi控件里拉一个TADOStoredProc,配置好相关链系,具体的操作列子如下: procedure TForm1.btnFirstClick(Sender: TObject); begin ...

  4. spring boot配置写法

    转自:http://blog.csdn.net/mickjoust/article/details/51646658 每日金句 你要搞清楚自己人生的剧本:不是你父母的续集,不是你子女的前传,更不是你朋 ...

  5. xcode6 自定义UITabbarController

    -(void)initTabBarView{ if (tabBarController && [kAPPDELEGATE.navigationController.viewContro ...

  6. 牛一网ecshop家电数码模板(仿易迅网)for ecshop 2.7.3

            本模板尤其适用于家电数码行业. 本模板已经开发.测试完毕,并开放演示. 本模板支持全站静态.销售数量后台自定义.首页商品独立图片.品牌独立展示.商品精美团购.宽屏窄屏自动识别并切换.分 ...

  7. AndroidのUI设计研究(一)——自定义ProgressBar

    最近迷上进度条,使用进度条可以增强用户体验,让用户心里有个底,再无奈的等待中体会loading的乐趣. 记得以前优乐美的官网,进入主页加载资源,显示给用户看的就是,炫彩背景下,一个杯子里的奶茶随着加载 ...

  8. javaHDU1003Max Sum

    import java.util.Scanner;  public class Sum  {public static void main(String args[])  {Scanner cin=n ...

  9. Java基础知识强化之IO流笔记44:IO流练习之 复制图片的 4 种方式案例

    1. 复制图片的 4 种方式案例: 分析: 复制数据,如果我们知道用记事本打开并能够读懂,就用字符流,否则用字节流. 通过该原理,我们知道我们应该采用字节流. 而字节流有4种方式,所以做这个题目我们有 ...

  10. 【亲测可用】MySQL 4.1迁移到MySQL 5.0版本的中文乱码问题解决

    核心:先导出结构,再导出数据. 结构最好使用myphpadmin导出.使用mysqldump导出的可能会导致一些问题. ---------------以下为转载---------------- 在生成 ...