LeetCode题解——Two Sum
题目地址: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的更多相关文章
- [LeetCode 题解] Combination Sum
前言 [LeetCode 题解]系列传送门: http://www.cnblogs.com/double-win/category/573499.html 1.题目描述 Given a se ...
- [LeetCode 题解]: Two Sum
前言 [LeetCode 题解]系列传送门: http://www.cnblogs.com/double-win/category/573499.html 1.题目描述 Given an a ...
- LeetCode题解之Sum Root to Leaf Numbers
1.题目描述 2.问题分析 记录所有路径上的值,然后转换为int求和. 3.代码 vector<string> s; int sumNumbers(TreeNode* root) { tr ...
- 回溯法 leetcode题解 Combination Sum 递归法
题目大意:给出一个数组,用这些数组里的元素去凑一个target.元素可以重复取用. 感觉对这种题目还是生疏的.脑子里有想法,但是不知道怎么表达出来. 先记录下自己的递归法.应该还可以用循环实现. 回溯 ...
- LeetCode题解之 Sum of Left Leaves
1.题目描述 2.问题分析 对于每个节点,如果其左子节点是叶子,则加上它的值,如果不是,递归,再对右子节点递归即可. 3.代码 int sumOfLeftLeaves(TreeNode* root) ...
- [LeetCode 题解]:Path Sum
前言 [LeetCode 题解]系列传送门: http://www.cnblogs.com/double-win/category/573499.html 1.题目描述 Given a bi ...
- [LeetCode] #167# Two Sum II : 数组/二分查找/双指针
一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...
- [LeetCode] #1# Two Sum : 数组/哈希表/二分查找/双指针
一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of ...
- 【LeetCode题解】二叉树的遍历
我准备开始一个新系列[LeetCode题解],用来记录刷LeetCode题,顺便复习一下数据结构与算法. 1. 二叉树 二叉树(binary tree)是一种极为普遍的数据结构,树的每一个节点最多只有 ...
随机推荐
- linux复制多个文件到文件夹
linux复制多个文件到文件夹 cp file1 file2 file3 directory即将文件file1 file2 file3复制到directory
- PAT-乙级-1003. 我要通过!(20)
1003. 我要通过!(20) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 CHEN, Yue “答案正确”是自动判题系统给出的最 ...
- uva 10562
二叉树的先序遍历 这个还是比较简单的 ~~ /************************************************************************* &g ...
- uva 10892
试了一下纯暴力 结果过了 无话可说 应该有更好的方法...... /**************************************************************** ...
- fiddler 插件开发
本文主要讲解使用.net C#语言开发Fiddler插件. 1.在Fiddler 会话列表中添加自定义列 使用FiddlerApplication.UI.lvSessions.AddBoundColu ...
- Windows10搭建PHP7开发环境
原文:Windows10搭建PHP7开发环境 3年前写了一篇<Windows下搭建PHP开发环境>之后就再也没有碰过PHP了,最近新发布了PHP7然后回去看了一下之前写的文章,发现很多配置 ...
- MyBatis的CRUD操作
MyBatis的两个主要配置文件 mytatis.xml:放在src目录下,常见的配置如下 <?xml version="1.0" encoding="UTF-8& ...
- R语言学习笔记:列表
R列表时以其他对象为成分的有序集合,列表的成分和向量不同,它们不一定是同一种数据类型,模式或者长度.例: > my.list<-list(stud.id=34453, + stud.nam ...
- WPF 中如何使用第三方控件 ,可以使用WindowsFormsHost 类
允许在 WPF 页面上承载 Windows Forms控件的元素. 命名空间: System.Windows.Forms.Integration 程序集: WindowsFormsIntegr ...
- 制作计算器的代码(C#)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...