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. Java Web基础入门

    前言 语言都是相通的,只要搞清楚概念后就可以编写代码了.而概念是需要学习成本的. Java基础 不用看<编程思想>,基础语法看 http://www.runoob.com/java/jav ...

  2. typescript入门基础

    1.typescript介绍 微软开发的一门编程语言,javascript的一个超集,遵循最新的ES6脚本语言规范(2015年发布),它扩展了Javascript的语法,任何已经写好的javascri ...

  3. Python后端开发要求

    关于Python后端开发要求 一.对Python有兴趣,熟悉Python(标准库) 最好阅读过源码 了解Python的优化(熟悉pypy更佳) 二.至少至少一门语言(不说"精通") ...

  4. MSSQL-并发控制-2-Isolation

              如果转载,请注明博文来源: www.cnblogs.com/xinysu/   ,版权归 博客园 苏家小萝卜 所有.望各位支持!   MySQL通过MVCC和锁来实现并发控制,在4 ...

  5. 微信小程序的网络设置,及网络请求:wx.request(OBJECT)

    Md2All 一个Markdown在线转换工具 网址:http://md.aclickall.com 微信公众号:颜家大少本文所用排版工具:http://md.aclickall.com 支持通用的M ...

  6. 鼠标相关操作(Cursor类及相关API)

    Cursor.visible:属性,显示或者隐藏鼠标.  Cursor.lockState = CursorLockMode.Locked:锁定鼠标到游戏窗口的中心. (CursorLockMode: ...

  7. Android - "cause failed to find target android-14" 问题

    在导入别人的工程项目时经常会遇到各种问题,本文中的就是其中SDK不对导致的   在导入项目时已经修改了 两个build.gradle文件 错误的原因是后面中这两项没修改. compileSdkVers ...

  8. 读Kafka Consumer源码

    最近一直在关注阿里的一个开源项目:OpenMessaging OpenMessaging, which includes the establishment of industry guideline ...

  9. 你绝不能错过的效率神器 —— Alfred

    文章首发于[博客园-陈树义],点击跳转到原文<你绝不能错过的效率神器 -- Alfred> Alfred 是 Mac 系统上一款专注于效率提升的著名应用,它能帮你快速打开网页.快速进行自定 ...

  10. 75、django之ORM补充

    本篇导航: QuerySet 中介模型 查询优化 一.QuerySet 1.可切片 使用Python 的切片语法来限制查询集记录的数目 .它等同于SQL 的LIMIT 和OFFSET 子句. > ...