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的更多相关文章

  1. Leetcode 1——twosum

    Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...

  2. LeetCode 之 TwoSum

    题目: Given an array of integers, find two numbers such that they add up to a specific target number. ...

  3. leetcode之twosum

    class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector& ...

  4. leetcode ----ARRAY TWOSUM

    代码的(判断nums[i]或者是target-nums[i]都可以):

  5. [LeetCode_1] twoSum

    LeetCode: 1. twoSum 题目描述 Given an array of integers, return indices of the two numbers such that the ...

  6. LeetCode 算法题解 js 版 (001 Two Sum)

    LeetCode 算法题解 js 版 (001 Two Sum) 两数之和 https://leetcode.com/problems/two-sum/submissions/ https://lee ...

  7. ANDROID学习书单

    Skip to content PersonalOpen sourceBusinessExplore Sign upSign in PricingBlogSupport   This reposito ...

  8. Android技能树

    第一部分:Android(安卓)Android基础知识Android内存泄漏总结Handler内存泄漏分析及解决Android性能优化ListView详解RecyclerView和ListView的异 ...

  9. LeetCode初体验—twoSum

    今天注册了大名鼎鼎的LeetCode,做了一道最简单的算法题目: Given an array of integers, return indices of the two numbers such ...

随机推荐

  1. insert时报Cannot add or update a child row: a foreign key constraint fails (`yanchangzichan`.`productstatusrecord`, CONSTRAINT `p_cu` FOREIGN KEY (`cid`) REFERENCES `customer` (`cid`))错误

    mybatis在insert时报Cannot add or update a child row: a foreign key constraint fails (`yanchangzichan`.` ...

  2. H5新增标签

    <!DOCTYPE html ><html><head><meta http-equiv="Content-Type" content=& ...

  3. Numpy入门 - 数组基本运算

    本节主要讲解numpy数组的基本运算,包括两数组相加.相减.相乘和相除. 一.两数组相加add import numpy as np arr1 = np.array([[1, 2, 3], [4, 5 ...

  4. SxsTrace程序追踪 && 错误信息分析

    先贴错误:应用程序无法运行,并行配置不正确 ,使用命令行sxstrace.exe.百度解决版本. 起因:同事给我一 EXE,然后基于 其进行开发 dll和模块,但是无法加入进程,无法运行. SxsTr ...

  5. 来自朝鲜的问候 golang入坑系列

    鸿渐于陆 本想着写满十八式,但按照目前的进度来看,是很难凑够十八式了.所以还是那句话,量力而行,适可而止.能写多少就写多少,我没法保证看完这本golang脱口秀,一定能成为golang大拿.但入了门, ...

  6. 腾讯 AI Lab 计算机视觉中心人脸 & OCR团队近期成果介绍(3)

    欢迎大家前往腾讯云社区,获取更多腾讯海量技术实践干货哦~ 作者:周景超 在上一期中介绍了我们团队部分已公开的国际领先的研究成果,近期我们有些新的成果和大家进一步分享. 1 人脸进展 人脸是最重要的视觉 ...

  7. DOM操作基本用法

    本文列举了js中DOM选取的基本用法,在列表中没有id的情况下如何选取到需要的一项,代码如下: <h2>获取Jerry的js代码</h2> <ul id="fi ...

  8. ibv_get_device_name()函数

    const char *ibv_get_device_name(struct ibv_device *device); 描述 函数用来获取一个与RDMA设备相关联的名字 注意 这个名字在一台特定的机器 ...

  9. Linux 进程间通信(包含一个经典的生产者消费者实例代码)

    前言:编写多进程程序时,有时不可避免的需要在多个进程之间传递数据,我们知道,进程的用户的地址空间是独立,父进程中对数据的修改并不会反映到子进程中,但内核是共享的,大多数进程间通信方式都是在内核中建立一 ...

  10. 来自Ext的UI边界识别函数constrain

    //constrain函数 var min = 1 var max = 3; var num = 4; var result = Math.min(Math.max(num,min),max); co ...