题目地址:https://oj.leetcode.com/problems/two-sum/

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

题目大意:

给定一个数组,找出其中两个数,它们的和等于给定的值。

函数返回这两个数的“下标”,下标按序排列,从1开始计算。

每个输入有且只有一个解。

分析:

①暴力解法。

  求每两个元素的和,时间为O(n2)。

②先排序,后查找 或者 左右夹逼。

  排序时间O(n logn),由于需要记录下标和元素值的关系,空间复杂度O(n)。然后:

  查找:对每一个元素a,二分查找target - a是否存在。总时间为O(n logn) + O(n logn) = O(n logn);

  夹逼:利用一对首尾指针求和,和<target,则首指针右移;和>target,则尾指针左移;相等则返回记录的下标值。总时间为O(n logn) + O(n) = O(n logn)。

③利用哈希表查找。

  哈希表记录元素对应下标,对于元素a,O(1)时间查找target - a是否存在。总时间为O(n)。

程序挂掉的几个测试用例

[5, 75, 25]  100      //排序之后下标顺序问题
[3, 2, 4]      6         //3 + 3 == 2 + 4  同一个元素被计算两次
[0, 4, 3, 0]  0         //0 + 0   元素重复,哈希表覆盖

代码:

 #include <iostream>
#include <vector>
#include <algorithm>
#include <tr1/unordered_map>
using namespace std;
using namespace tr1; //②先排序,再夹逼。用一个辅助struct来记录数据和下标信息,并自定义比较函数,来对struct数组排序。
struct node{
int data;
int index;
node(int _data, int _index): data(_data), index(_index)
{
}
}; bool myCmp(node n1, node n2)
{
return n1.data < n2.data;
} vector<int> twoSum1(const vector<int> &numbers, int target)
{
vector<int> result; if(numbers.empty())
{
return result;
} vector<node> nv; //space: O(N)
for(int i = ; i < numbers.size(); ++i) //time: O(N)
{
nv.push_back( node(numbers[i], i) );
} sort(nv.begin(), nv.end(), myCmp); //排序,time: O(NlgN) int hIdx = , tIdx = nv.size() - ; while(hIdx < tIdx) //夹逼,time: O(N)
{
int sum = nv[hIdx].data + nv[tIdx].data; if(sum == target)
{
result.push_back(min(nv[hIdx].index, nv[tIdx].index) + );//min、max来确保下标顺序
result.push_back(max(nv[hIdx].index, nv[tIdx].index) + );
break;
}
else if(sum < target)
{
++hIdx;
}
else
{
--tIdx;
}
} //while return result;
} //③哈希表,由数据映射到下标,相同数据只记录最后一个下标。
vector<int> twoSum2(const vector<int> &numbers, int target)
{
vector<int> result; if(numbers.empty())
{
return result;
} unordered_map<int, int> num2loc; //space: O(N)
for(int i = ; i < numbers.size(); ++i) //哈希映射,time: O(N)
{
num2loc[ numbers[i] ] = i;
} for(int i = ; i < numbers.size() - ; ++i) //查找,time: O(N)
{
int gap = target - numbers[i]; if( num2loc.find(gap) != num2loc.end() && num2loc[gap] > i )
{
result.push_back(i + );
result.push_back(num2loc[gap] + );
break;
}
} return result;
} int main()
{
int nums[] = {,,,};
vector<int> numbers(nums, nums + sizeof(nums)/sizeof(*nums));
int target = ; vector<int> result; result = twoSum1(numbers, target);
for(int i = ; i < result.size(); ++i)
{
cout << result[i] << ' ';
}
cout << endl; result = twoSum2(numbers, target);
for(int i = ; i < result.size(); ++i)
{
cout << result[i] << ' ';
}
cout << endl; return ;
}

LeetCode题解——Two Sum的更多相关文章

  1. [LeetCode 题解] Combination Sum

    前言   [LeetCode 题解]系列传送门:  http://www.cnblogs.com/double-win/category/573499.html   1.题目描述 Given a se ...

  2. [LeetCode 题解]: Two Sum

    前言   [LeetCode 题解]系列传送门:  http://www.cnblogs.com/double-win/category/573499.html   1.题目描述 Given an a ...

  3. LeetCode题解之Sum Root to Leaf Numbers

    1.题目描述 2.问题分析 记录所有路径上的值,然后转换为int求和. 3.代码 vector<string> s; int sumNumbers(TreeNode* root) { tr ...

  4. 回溯法 leetcode题解 Combination Sum 递归法

    题目大意:给出一个数组,用这些数组里的元素去凑一个target.元素可以重复取用. 感觉对这种题目还是生疏的.脑子里有想法,但是不知道怎么表达出来. 先记录下自己的递归法.应该还可以用循环实现. 回溯 ...

  5. LeetCode题解之 Sum of Left Leaves

    1.题目描述 2.问题分析 对于每个节点,如果其左子节点是叶子,则加上它的值,如果不是,递归,再对右子节点递归即可. 3.代码 int sumOfLeftLeaves(TreeNode* root) ...

  6. [LeetCode 题解]:Path Sum

    前言   [LeetCode 题解]系列传送门:  http://www.cnblogs.com/double-win/category/573499.html   1.题目描述 Given a bi ...

  7. [LeetCode] #167# Two Sum II : 数组/二分查找/双指针

    一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...

  8. [LeetCode] #1# Two Sum : 数组/哈希表/二分查找/双指针

    一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of ...

  9. 【LeetCode题解】二叉树的遍历

    我准备开始一个新系列[LeetCode题解],用来记录刷LeetCode题,顺便复习一下数据结构与算法. 1. 二叉树 二叉树(binary tree)是一种极为普遍的数据结构,树的每一个节点最多只有 ...

随机推荐

  1. Linux计算机进程地址空间与内核装载ELF

    本文基于Linux™系统对进程创建与加载进行分析,文中实现了Linux库函数fork.exec,剖析内核态执行过程,并进一步展示进程创建过程中进程控制块字段变化信息及ELF文件加载过程. 一.初识Li ...

  2. Java-使用js进行编码,后台解码。

    1:使用js编码 var value=window.encodeURI(window.encodeURI(strValue)); 2:Java类中解码. String str=URLDecoder.d ...

  3. spring mvc中的@PathVariable(转)

    鸣谢:http://jackyrong.iteye.com/blog/2059307 ------------------------------------------------ spring m ...

  4. HDU4602+推导公式

    手动列出前5项 可发现规律 /* 推导公式 a[n] = 2^(n-1) + (n-2)*2^(n-3) */ #include<stdio.h> #include<math.h&g ...

  5. JS作用域与闭包--实例

    <script> "use strict" //函数作用域 function func(){ var arr = [1,3,5,7,9]; var sum = 0; f ...

  6. [itint5]根据前序后序遍历统计二叉树

    http://www.itint5.com/oj/#28 这题有意思.一开始还想不清楚,看了解释,很棒. 这个题目的特殊之处是所有节点的值都是不一样的. 所以递归过程可以大大简化. 先看两种遍历的性质 ...

  7. RGB颜色查询对照表

    RGB颜色查询对照表     RGB颜色对照表   #FFFFFF2015-02-05   #FFFFF0   #FFFFE0   #FFFF00   #FFFAFA   #FFFAF0   #FFF ...

  8. Upload/download/UrlConnection/URL

    文件上传的核心点 1:用<input type=”file”/> 来声明一个文件域.File:_____ <浏览>. 2:必须要使用post方式的表单. 3:必须设置表单的类型 ...

  9. Zookeeper命令

    常用命令 ZooKeeper 支持某些特定的四字命令字母与其的交互.它们大多是查询命令,用来获取 ZooKeeper 服务的当前状态及相关信息.用户在客户端可以通过 telnet 或 nc 向 Zoo ...

  10. 1470. UFOs(三维树状数组)

    1470 最简单的三维树状数组 #include <iostream> #include<cstdio> #include<cstring> #include< ...