2 Sum
Problem
Given an array of integers, find two numbers such that they add up to aspecific target number. The function twoSum should return indices of the two numbers such thatthey add up to the target, where index1 must be less than index2. Please notethat your returned answers (both index1 and index2) are NOT zero-based. Example
numbers=[, , , ], target= return [, ] Note
You may assume that each input would have exactly one solution Challenge
Either of the following solutions are acceptable: O(n) Space, O(nlogn) Time
O(n) Space, O(n) Time
题解1 - 哈希表
找两数之和是否为target, 如果是找数组中一个值为target该多好啊!遍历一次就知道了,我只想说,too naive... 难道要将数组中所有元素的两两组合都求出来与target比较吗?时间复杂度显然为 O(n2), 显然不符题目要求。找一个数时直接遍历即可,那么可不可以将两个数之和转换为找一个数呢?我们先来看看两数之和为target所对应的判断条件—— xi+xj=target, 可进一步转化为 xi=target−xj, 其中 i 和 j 为数组中的下标。一段神奇的数学推理就将找两数之和转化为了找一个数是否在数组中了!可见数学是多么的重要...
基本思路有了,现在就来看看怎么实现,显然我们需要额外的空间(也就是哈希表)来保存已经处理过的 xj(注意这里并不能先初始化哈希表,否则无法排除两个相同的元素相加为 target 的情况), 如果不满足等式条件,那么我们就往后遍历,并把之前的元素加入到哈希表中,如果target减去当前索引后的值在哈希表中找到了,那么就将哈希表中相应的索引返回,大功告成!
C++:
class Solution {
public:
/*
* @param numbers : An array of Integer
* @param target : target = numbers[index1] + numbers[index2]
* @return : [index1+1, index2+1] (index1 < index2)
*/
vector<int> twoSum(vector<int> &nums, int target) {
vector<int> result;
const int length = nums.size();
if ( == length) {
return result;
}
// first value, second index
unordered_map<int, int> hash(length);
for (int i = ; i != length; ++i) {
if (hash.find(target - nums[i]) != hash.end()) {
result.push_back(hash[target - nums[i]]);
result.push_back(i + );
return result;
} else {
hash[nums[i]] = i + ;
}
}
return result;
}
};
JAVA:
public class Solution {
/*
* @param numbers : An array of Integer
* @param target : target = numbers[index1] + numbers[index2]
* @return : [index1 + 1, index2 + 1] (index1 < index2)
*/
public int[] twoSum(int[] numbers, int target) {
if (numbers == null || numbers.length == 0) return new int[]{0, 0};
Map<Integer, Integer> hashmap = new HashMap<Integer, Integer>();
int index1 = 0, index2 = 0;
for (int i = 0; i < numbers.length; i++) {
if (hashmap.containsKey(target - numbers[i])) {
index1 = hashmap.get(target - numbers[i]);
index2 = i;
return new int[]{1 + index1, 1 + index2};
} else {
hashmap.put(numbers[i], i);
}
}
return new int[]{0, 0};
}
}
源码分析
- 异常处理。
- 使用 C++ 11 中的哈希表实现
unordered_map映射值和索引。Python 中的dict就是天然的哈希表。 - 找到满足条件的解就返回,找不到就加入哈希表中。注意题中要求返回索引值的含义。
复杂度分析
哈希表用了和数组等长的空间,空间复杂度为 O(n), 遍历一次数组,时间复杂度为 O(n).
题解2 - 排序后使用两根指针
但凡可以用空间换时间的做法,往往也可以使用时间换空间。另外一个容易想到的思路就是先对数组排序,然后使用两根指针分别指向首尾元素,逐步向中间靠拢,直至找到满足条件的索引为止。
C++:
class Solution {
public:
/*
* @param numbers : An array of Integer
* @param target : target = numbers[index1] + numbers[index2]
* @return : [index1+1, index2+1] (index1 < index2)
*/
vector<int> twoSum(vector<int> &nums, int target) {
vector<int> result;
const int length = nums.size();
if ( == length) {
return result;
}
// first num, second is index
vector<pair<int, int> > num_index(length);
// map num value and index
for (int i = ; i != length; ++i) {
num_index[i].first = nums[i];
num_index[i].second = i + ;
}
sort(num_index.begin(), num_index.end());
int start = , end = length - ;
while (start < end) {
if (num_index[start].first + num_index[end].first > target) {
--end;
} else if(num_index[start].first + num_index[end].first == target) {
int min_index = min(num_index[start].second, num_index[end].second);
int max_index = max(num_index[start].second, num_index[end].second);
result.push_back(min_index);
result.push_back(max_index);
return result;
} else {
++start;
}
}
return result;
}
};
源码分析
- 异常处理。
- 使用
length保存数组的长度,避免反复调用nums.size()造成性能损失。 - 使用
pair组合排序前的值和索引,避免排序后找不到原有索引信息。 - 使用标准库函数排序。
- 两根指针指头尾,逐步靠拢。
复杂度分析
遍历一次原数组得到pair类型的新数组,时间复杂度为 O(n), 空间复杂度也为 O(n). 标准库中的排序方法时间复杂度近似为 O(nlogn), 两根指针遍历数组时间复杂度为 O(n).
2 Sum的更多相关文章
- LeetCode - Two Sum
Two Sum 題目連結 官網題目說明: 解法: 從給定的一組值內找出第一組兩數相加剛好等於給定的目標值,暴力解很簡單(只會這樣= =),兩個迴圈,只要找到相加的值就跳出. /// <summa ...
- Leetcode 笔记 113 - Path Sum II
题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...
- Leetcode 笔记 112 - Path Sum
题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...
- POJ 2739. Sum of Consecutive Prime Numbers
Sum of Consecutive Prime Numbers Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 20050 ...
- BZOJ 3944 Sum
题目链接:Sum 嗯--不要在意--我发这篇博客只是为了保存一下杜教筛的板子的-- 你说你不会杜教筛?有一篇博客写的很好,看完应该就会了-- 这道题就是杜教筛板子题,也没什么好讲的-- 下面贴代码(不 ...
- [LeetCode] Path Sum III 二叉树的路径和之三
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- [LeetCode] Partition Equal Subset Sum 相同子集和分割
Given a non-empty array containing only positive integers, find if the array can be partitioned into ...
- [LeetCode] Split Array Largest Sum 分割数组的最大值
Given an array which consists of non-negative integers and an integer m, you can split the array int ...
- [LeetCode] Sum of Left Leaves 左子叶之和
Find the sum of all left leaves in a given binary tree. Example: 3 / \ 9 20 / \ 15 7 There are two l ...
- [LeetCode] Combination Sum IV 组合之和之四
Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...
随机推荐
- 把文档转化为PDF再用PS处理PDF
最近工作中遇到类似下面这样的一个文档. 文档当前设置的是A4 横版打印,可以明显的看到打印的分界线,这样直接打印出来,是没有下面那行“bbbbbbbbbbbbbbbbbb”的,怎么办?可以通过 页面布 ...
- 算法Sedgewick第四版-第1章基础-006一封装输出(文件)
1. package algorithms.util; /*********************************************************************** ...
- ZROI2018提高day5t3
传送门 分析我们可以根据性质将这个序列构造成一个环:0,a[1~n],0,a[n~1] 这中间的0是为了起间隔作用的. 我们又知道b[i]=a[i-1]^a[i+1] c[i]=b[i-1]^b[i+ ...
- Luogu 2831 [NOIP2016] 愤怒的小鸟
第一眼看成爆搜的状压dp,膜Chester大神犇. 考虑到三个不在同一直线上的点可以确定一条抛物线,而固定点$(0, 0)$和不在同一直线上这两个条件是题目中给定的,所以我们只要枚举两个点然后暴力算抛 ...
- ubuntu 12.04 (64位)下安装oracle 11g过程及问题总结
最近公司用到oracle,在ubuntu64位安装了一下,碰到了一些问题,在网上搜索到了一些答案,在此作为笔记记录下来. 1.首先下载oracle并解压不再赘述. 2.安装依赖包 sudo apt-g ...
- TinkerPop中的遍历:图的遍历策略
遍历策略 一个TraversalStrategy分析一个遍历,如果遍历符合它的标准,可以相应地改变它.遍历策略在编译时被执行,并构成Gremlin遍历机的编译器的基础.有五类策略分列如下: decor ...
- WCF寄宿控制台.WindowsService.WinFrom.WebAPI寄宿控制台和windows服务
先建立wcf类库.会默认生成一些试用代码.如下: public class Service1 { public string GetData(int value) { return string.Fo ...
- C#调用WCF问题汇总
1.添加服务后无法引用,添加服务时打开高级,将下面的选项去掉就可以引用了. 2.在程序中引用后,运行时报“找不到引用协定‘’的默认终结点元素”错误,这是由于在工程的App.config里没有生成配置节 ...
- C# 添加,修改,删除Xml节点
//添加xml节点 private void AddXml(string image, string title) { XmlDocument xmlDoc = new X ...
- LinkedList实现原理
原文链接:https://www.jianshu.com/p/56c77c517e71 本文对LinkedList的实现讨论都基于JDK8版本 Java中的LinkedList类实现了List接口和D ...