LeetCode #1 TwoSum
Description
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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路
首先我们想到的是暴力法,两个 for 循环求解,时间复杂度为O(n^2)
//Runtime: 106 ms
//First thought: BF
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int i,j;
vector<int> ret {, };
for (i = ; i< nums.size(); ++i) {
ret[] = i;
for(j = i+; j < nums.size(); ++j){
if (nums[i] + nums[j] == target)
{
ret[] = j;
return ret;
}
}
}
}
};
但是,我发现时间消耗太多了,所以借鉴当时“换硬币”、“爬楼梯”问题的优化方法,由于num[i]、num[j]、target都是定值,所以在条件判断里不需要每次都进行加运算
//Runtime: 79 ms
//Because nums[i], nums[j], target are fixed values, we do not need to do additions every time
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int i,j;
vector<int> ret {, };
for (i = ; i< nums.size(); ++i) {
ret[] = i;
int tar = target - nums[i];
for(j = i+; j < nums.size(); ++j){
if (nums[j] == tar)
{
ret[] = j;
return ret;
}
}
}
}
};
AC后,看了 Discuss 里头的方法以及娄神的博客,我采用了更复杂的数据结构 散列表(HashTable)以降低时间复杂度,我的想法是这样: 如果想只扫描一遍数组就得出结果,那么肯定就要有一部字典,边扫描边存储值,在这里存储的不是数组当前的值,而是“目标值 - 当前值”,我们称之为对象值。
也就是说,字典里存储的是每个数据所希望的”另一半“的大小。所以,字典的 Key 是对象值,字典的 Value 是数组索引。然后我们再往后扫描,如果扫描到的值的另一半出现在了字典里,那么说明当前值是”上一半“所需要的”下一半“,此时将它们的索引存储在 ret[0]、ret[1]中并返回;如果没有字典里没有出现它的另一半,那么把对象值和当前索引继续存储字典中。
该算法的时间复杂度为 O(n)
//Runtime: 6 ms #include<unordered_map>
using std::unordered_map; class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> um;
vector<int> res();
int i;
int n = nums.size();
for (i = ; i < n; ++i) {
if (um.find(target - nums[i]) != um.end()) {
res[] = um[target - nums[i]];
res[] = i;
return res;
}
else {
um[nums[i]] = i;
}
}
um.clear();
}
};
补充一种双指针遍历有序数组的方法
TwoNumberSum (S, x)
mergeSort (S, , n)
i =
j = n
while i < j
if A[i] + A[j] == x
return true
if A[i] + A[j] < x
i = i +
if A[i] + A[j] > x
j = j -
return false
可以看得出来,查找的时间仅需 Θ(n),所以时间总代价受排序时间代价的影响,为Θ(n lgn)
扫描的原理很简单,先设 mi,j : A[i] + A[j] < S,Mi,j : A[i] + A[j] > S 。由于序列已排序,则 mi,j ⇒∀k < j 都有 mi,k 成立,并且 Mi,j ⇒ ∀k > i 都有 Mk,j 成立
LeetCode #1 TwoSum的更多相关文章
- Leetcode 1——twosum
Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...
- LeetCode 之 TwoSum
题目: Given an array of integers, find two numbers such that they add up to a specific target number. ...
- leetcode之twosum
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector& ...
- leetcode ----ARRAY TWOSUM
代码的(判断nums[i]或者是target-nums[i]都可以):
- [LeetCode_1] twoSum
LeetCode: 1. twoSum 题目描述 Given an array of integers, return indices of the two numbers such that the ...
- LeetCode 算法题解 js 版 (001 Two Sum)
LeetCode 算法题解 js 版 (001 Two Sum) 两数之和 https://leetcode.com/problems/two-sum/submissions/ https://lee ...
- ANDROID学习书单
Skip to content PersonalOpen sourceBusinessExplore Sign upSign in PricingBlogSupport This reposito ...
- Android技能树
第一部分:Android(安卓)Android基础知识Android内存泄漏总结Handler内存泄漏分析及解决Android性能优化ListView详解RecyclerView和ListView的异 ...
- LeetCode初体验—twoSum
今天注册了大名鼎鼎的LeetCode,做了一道最简单的算法题目: Given an array of integers, return indices of the two numbers such ...
随机推荐
- 【SpringMVC】使用Myeclipse创建SpringMVC项目【超详细教程】
之前一直是使用Eclipse创建Web项目,用IDEA和MyEclipse的创建SpringMVC项目的时候时不时会遇到一些问题,这里把这个过程记录一下,希望能帮助到那些有需要的朋友.我是用的是MyE ...
- Entity Framework Core 使用HiLo生成主键
#cnblogs_post_body.cnblogs-markdown p img { max-width: 95%; } HiLo是在NHiernate中生成主键的一种方式,不过现在我们可以在Ent ...
- ExceptionLess 本地部署小结
ExceptionLess 是一个免费开源分布式系统日志收集框架,地址:https://github.com/exceptionless/Exceptionless 运行环境: .NET 4.6.1 ...
- c语言的extern与static与递归
知识点: 外部函数:定义的函数能被本文件和其他文件访问 1> 默认情况下所有函数都是外部函数 2> 不允许有同名的外部函数 内部函数:定义的函数只能被本文件访问,其他文件不能访问 1> ...
- States字段的使用规范
背景 为了统一数据库表的状态字段,统一数据库表设计,简化字段在程序开发中的使用方式. 解决方式 States对应位域枚举StatesFlags. /// <summary> /// 数据状 ...
- Flask中使用Flask-Migrate扩展迁移数据库
安装Flask-Migrate插件 (venv) $ pip install flask-migrate 注意到虚拟环境中(因为Flask环境就安装在虚拟环境中) 安装flask-script使pyt ...
- PHP进程锁
<?php /** * CacheLock 进程锁,主要用来进行cache失效时的单进程cache获取,防止过多的SQL请求穿透到数据库 * 用于解决PHP在并发时候的锁控制,通过文件/eacc ...
- 生成ssl秘钥的方法(纯粹本人记录用的,勿踩)
openssl genrsa -des3 -out server.key 1024 openssl req -new -key server.key -out server.csr cp server ...
- PHP提高网站性能的一些方法
前段时间面试问到了这个问题,回答的不是很全面,就去问了度娘,得到了一些比较全的答案,由于出处较多就没法确定原文出处了.下面是分享的答案. 一.大型网站性能提高策略: 大型网站,比如门户网站,在面对大量 ...
- YiShop_做一个b2c商城要多少钱
[YiShop商城系统]做一个b2c商城要多少钱?是企业在做一个b2c商城最关心的问题.每个企业都是想用最少的钱做一个好的b2c商城.但企业这种想法可能在现实中是无法实现的.网站这种产品现实中是一分钱 ...