Problem: 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:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

该题最容易想到的暴力解法就是两层循环,逐对相加与target比较。其代价过大,代码为:

 class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
unordered_map<int,int> hash;
for(int i = ; i < nums.size(); i++)
{
int num_to_find = target - nums[i];
if(hash.find(num_to_find) != hash.end())
{
result.push_back(hash[num_to_find]);
result.push_back(i);
return result;
}
else
{
hash[nums[i]] = i;
}
}
return result;
}
};

时间复杂度为O(n)的做法是只遍历一次vector,然后用hash表的find快速查找存储的数字。其代码如下:

 class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
unordered_map<int,int> hash;
for(int i = ; i < nums.size(); i++)
{
int num_to_find = target - nums[i];
if(hash.find(num_to_find) != hash.end())
{
result.push_back(hash[num_to_find]);
result.push_back(i);
return result;
}
else
{
hash[nums[i]] = i;
}
}
return result;
}
};

已遇到多题巧用hash table(unordered_map)简化算法的方法,注意hash table的使用!

LeetCode 1. Two Sum的更多相关文章

  1. Java for LeetCode 216 Combination Sum III

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

  2. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  3. [leetCode][013] Two Sum 2

    题目: Given an array of integers that is already sorted in ascending order, find two numbers such that ...

  4. [LeetCode] #167# Two Sum II : 数组/二分查找/双指针

    一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...

  5. [LeetCode] #1# Two Sum : 数组/哈希表/二分查找/双指针

    一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of ...

  6. [array] leetcode - 40. Combination Sum II - Medium

    leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...

  7. [array] leetcode - 39. Combination Sum - Medium

    leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without dup ...

  8. LeetCode one Two Sum

    LeetCode one Two Sum (JAVA) 简介:给定一个数组和目标值,寻找数组中符合求和条件的两个数. 问题详解: 给定一个数据类型为int的数组,一个数据类型为int的目标值targe ...

  9. [leetcode]40. Combination Sum II组合之和之二

    Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...

  10. [LeetCode] 437. Path Sum III_ Easy tag: DFS

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

随机推荐

  1. mysql 中基础英语单词 (一)关于数据库创建与查找 (包括简写单词)

    create 创建             limit 限制        count  计算     rollup  几上归纳 drop   降下,撤销                       ...

  2. MyBatis中关于别名typeAliases的设置

    第一种:通过在配置文件中typeAlias节点设置type的方式 <?xml version="1.0" encoding="UTF-8" ?> & ...

  3. EXTJS中grid的数据特殊显示,不同窗口的数据传递

    //EXTJS中grid的数据特殊显示renderer : function(value, metaData, record, rowIndex, colIndex, store, view) { v ...

  4. iOS 强制退出程序APP代码

    1.先po代码 UIAlertView* alert = [[UIAlertView alloc] initWithTitle:self.exitapplication message:@" ...

  5. js 判断客户端浏览器

    var browser={ versions:function(){ var u = navigator.userAgent, app = navigator.appVersion; return { ...

  6. phalcon3.0.1默认多模块生成的几个bug

    发现用Phalcon DevTools (3.0.0)生成的多模块有一些bug: 默认的路由定义,字符串替换有误 原代码// $namespace = str_replace('Module','Co ...

  7. How to use Bundle&Minifier and bundleconfig.json in ASP.NET Core

    引言 我们在ASP.NET MVC 中经常会用到 bundleConfig.cs 文件来进行我们 css 和 js 的绑定, 那么在ASP.NET Core 中我们应该如何使用呢? 步骤一 在 Vis ...

  8. How the problem solved about " Dealing with non-fast-forward errors"

    Recently ,I got confused When I use  git to push one of my project. The problem is below: And I Foun ...

  9. MVC 文件上传问题

    在用MVC作文件上传处理时,最开始是这样的. html代码 <div id="dialog" title="Upload files">       ...

  10. CentOS7下安装配置MariaDB

    参考: http://www.2cto.com/os/201504/394141.html http://outofmemory.cn/code-snippet/2533/mysql-create-d ...