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. IDEA安装步骤详解

    IDEA开发工具是java语言开发的集成环境,IntelliJ在业界被公认为最好的java开发工具之一,尤其在智能代码助手.代码自动提示.重构.J2EE支持.各类版本工具(git.svn.github ...

  2. IMDB TOP 250爬虫

    这个小学期Python大作业搞了个获取IMDB TOP 250电影全部信息的爬虫.第二次写爬虫,比在暑假集训时写的熟练多了.欢迎大家评论. ''' ************************** ...

  3. spring学习笔记(一) Spring概述

    博主Spring学习笔记整理大部分内容来自Spring实战(第四版)这本书.  强烈建议新手购入或者需要电子书的留言. 在学习Spring之前,我们要了解这么几个问题:什么是Spring?Spring ...

  4. Kaggle初入门

    今天成功的进驻kaggle社区了! 所以以后就要跟kaggle上面的各位一起学习啦! 今天十分成功的在tensorflow的环境里面装了一堆库--什么seaborn啊pandas啊都一次过 然后--并 ...

  5. androidStudio 中 gradle 常用功能

    1. gradle 使用 svn 当前版本信息. def getSvnRevision() { new ByteArrayOutputStream().withStream { os -> de ...

  6. 超简单的php缓存类

    <?php class Cache { private $dir = "data/cache/";//定义缓存目录 private $key='c_a_sss'; // 文件 ...

  7. 认知服务调用如何使用图片的DataURL

    说明: Data URL给了我们一种很巧妙的将图片"嵌入"到HTML中的方法.跟传统的用img标记将服务器上的图片引用到页面中的方式不一样,在Data URL协议中,图片被转换成b ...

  8. 初学web前端 ,请大家多多提意见 前几天学的 学写盒子模型

    <!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8&qu ...

  9. 剑指Offer_6_从尾到头打印链表

    题目描述        输入应该链表的头节点 , 从尾到头反过来打印出每个节点的值.链表定义如下 : typedef struct ListNode { int m_nKey ; ListNode * ...

  10. 使用.Net Core+EF7 CodeFirst(2)

    上一篇的话,说了下怎么使用EF7 实现 CodeFirst去生成数据库, 其实还有好多问题的,这次一点一点的解决吧,都挺简单,不过零零散散的,, 1.读取配置文件,获得链接字符串 2.使用数据库进行增 ...