LeetCode twoSum
2016-03-21 22:30
429 查看
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
Subscribe to see which companies asked this question
Hide Tags
Array Hash Table
Show Similar Problems
大致的问题:给定一个整形数组,返回一个两数之和等于给定目标的目录。你可以假定每次输入只有一个解决办法
我首先想到的是,一个一个的解决,时间复杂度为(n²),空间复杂度为(1)
代码如下,结果是当数组的长度过大时,会超时。
只能牺牲空间复杂度,来提升时间复杂度。而且题目中的tags有hash table,在C++中可以用map来代替,于是求得下列结果
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
Subscribe to see which companies asked this question
Hide Tags
Array Hash Table
Show Similar Problems
大致的问题:给定一个整形数组,返回一个两数之和等于给定目标的目录。你可以假定每次输入只有一个解决办法
我首先想到的是,一个一个的解决,时间复杂度为(n²),空间复杂度为(1)
代码如下,结果是当数组的长度过大时,会超时。
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> results; auto len = nums.size(); for (int i = 0; i<len || nums[i] >= target; ++i) { int j = i + 1; for (; j<len || nums[j] > target; ++j) { if ((nums[i] + nums[j]) == target) { results.push_back(i); results.push_back(j); break; } } if ((nums[i] + nums[j]) == target) break; } return results; } }
只能牺牲空间复杂度,来提升时间复杂度。而且题目中的tags有hash table,在C++中可以用map来代替,于是求得下列结果
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> result; map<int, int> m; if (nums.size() < 2) return result; for (int i = 0; i < nums.size(); i++) m[nums[i]] = i;//建立hash表 map<int, int>::iterator it; for (int i = 0; i < nums.size(); i++) { if ((it = m.find(target - nums[i])) != m.end()) { if (i == it->second) continue; result.push_back(i); result.push_back(it->second);//将结果放入到result中 return result; } } return result; } };
相关文章推荐
- 使用css Flexbox实现垂直居中
- Ubuntu 下如何设置 Java 环境变量
- codeforces 598E E. Chocolate Bar(区间dp)
- 0321《构建之法》现代软件工程第1、2、3章读后感
- PAT 乙级 1019. 数字黑洞
- 深入 PHP 面向对象、模式与实践
- C#学习笔记 线程同步问题
- 计算次数,POJ(1207)
- Android style用法
- 对称密钥与非对称密钥算法
- nginx conf文件结构介绍以及相关配置
- Unity5的AssetBundle的一点使用心得
- lintCode(114)——不同的路径
- 做程序员第二十天
- 整理一些C++面试容易被问到的问题及其答案
- WMI Attacks
- java第十四节-Collection接口-List
- 去除字符串中的空格
- 浏览器兼容性问题汇总及解决方案
- 前端工程师切图技能——PS工具准备