题目:输入一个已经按升序排序过的数组和一个数字,

在数组中查找两个数,使得它们的和正好是输入的那个数字。

要求时间复杂度是 O(n)。如果有多对数字的和等于输入的数字,输出任意一对即可。

例如输入数组 1、2、4、7、11、15 和数字 15。由于 4+11=15,因此输出 4 和 11。

分析:

给出两种算法: 1. 枚举第一个,然后二分搜索第二个数。 O(NlgN)

2. 双指针法。 left, right 分别指向首尾,如果 a[left] + a[right] < sum, left++,  如果 >, right --; 否则 找到答案

扩充:找出 3个数,使其和等于 sum. 见 点击打开链接

// copyright @ L.J.SHOU Mar.05, 2014
// 2 sum
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std; // O(NlgN)
void TwoSumVersion1(vector<int> &a, int sum)
{
if(a.size() < 2)
return; for(vector<int>::iterator it = a.begin(); it != a.end(); ++it)
{
if(binary_search(a.begin(), it, sum - *it)
|| binary_search(it+1, a.end(), sum - *it))
{
cout << *it << " " << sum - *it << endl;
return;
}
}
} // two pointers O(N)
void TwoSumVersion2(vector<int> &a, int sum)
{
vector<int>::iterator left(a.begin()), right(a.end()-1); while(left < right)
{
if(*left + *right < sum){
++ left;
}
else if(*left + *right > sum){
-- right;
}
else{
cout << *left << " " << *right << endl;
return;
}
}
} int main(void)
{
int a[]={1,2,4,7,11,15};
vector<int> vec(a, a+sizeof(a)/sizeof(int)); TwoSumVersion1(vec, 15);
TwoSumVersion2(vec, 15); return 0;
}

Interview----2 sum的更多相关文章

  1. 行列转换文本处理--awk xargs 回顾

    awk 数组回顾: 9.1 数组 举例:统计当前主机上每一个TCP连接状态以及每种连接状态的数目[非常实用] # netstat -tan | awk '/^tcp/{STATE[$NF]++}END ...

  2. Amazon Interview | Set 27

    Amazon Interview | Set 27 Hi, I was recently interviewed for SDE1 position for Amazon and got select ...

  3. [转]Design Pattern Interview Questions - Part 4

    Bridge Pattern, Composite Pattern, Decorator Pattern, Facade Pattern, COR Pattern, Proxy Pattern, te ...

  4. [LintCode] Two Sum 两数之和

    Given an array of integers, find two numbers such that they add up to a specific target number. The ...

  5. [LintCode] Continuous Subarray Sum 连续子数组之和

    Given an integer array, find a continuous subarray where the sum of numbers is the biggest. Your cod ...

  6. [LintCode] Submatrix Sum 子矩阵之和

    Given an integer matrix, find a submatrix where the sum of numbers is zero. Your code should return ...

  7. [LintCode] Minimum Size Subarray Sum 最小子数组和的大小

    Given an array of n positive integers and a positive integer s, find the minimal length of a subarra ...

  8. k Sum | & ||

    k Sum Given n distinct positive integers, integer k (k <= n) and a number target. Find k numbers ...

  9. Lintcode: Interval Sum II

    Given an integer array in the construct method, implement two methods query(start, end) and modify(i ...

  10. Lintcode: Interval Sum

    Given an integer array (index from 0 to n-1, where n is the size of this array), and an query list. ...

随机推荐

  1. nodeschool.io 10

    ~~ TIME SERVER ~~ Write a TCP time server! Your server should listen to TCP connections on port 8000 ...

  2. github如何pull最新代码

      github现在已经经常用了,但是经常遇到下面的问题 比如:从一个项目A中fork了一个分支B,并且在分支B有了改动.过了几天后,项目A中的代码应该会有很多人提交修改了,现在想将最新的代码pull ...

  3. 在jsp页面解析json的2种方法

    方法1: $(function() { $("#btn").click(function() { $.ajax({ url : "fastjson.do", s ...

  4. Extjs jar包问题

    当前使用struts2.23版本,使用用了jsonplugin-0.3x.jar报: com.opensymphony.xwork2.util.TextUtils错. json-lib-2.x.jar ...

  5. placeholder在ie789下无效

    <input type="text" class="input" placeholder="用户名/手机号码/邮箱" value=&q ...

  6. CentOS 6.2下SVN服务器的安装与配置

    安装了一下SVN服务器,本文没有与Apache整合,过程如下: 一,下载相关软件: [root@youxia201 test]# wget http://subversion.tigris.org/d ...

  7. 使用ServerSocket创建TCP服务器端

    在两个通信实体没有建立虚拟链路之前,必须有一个通信实体先做出“主动姿态”,主动接受来自其他通信实体的连接请求. Java中能接受其它通信实体连接请求的类是ServerSocket,ServerSock ...

  8. [示例]NSDictionary编程题-字典的排序应用(iOS4班)

    代码: #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepo ...

  9. (DFS)zoj1008-Gnome Tetravex

    现在zoj暂时关了,实际上是在scuoj上做的. 题目地址 看起来题目比较复杂,实际上主要需要思维的是如何恰当的剪枝及合适的DFS角度. 问题等价于将n*n个可能相同的方块放到一个n*n的表中,使满足 ...

  10. sql思维

    写sql的思路不同于常规编程语言(C.python)等等.前者,考虑如何一步步地得到最终答案:后者,考虑如何一步步地收缩数据范围. 简而言之,前者是面向过程化(for each row do x),后 ...