题目:

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 = [, , , ], target = ,

Because nums[] + nums[] =  +  = ,
return [, ].

题解:

  首先想到暴力解,TLE(Time Limit Exceeded)问题先不考虑。从数组头开始,依次与其他元素比较,然后向后移动开始位置,需要注意的是返回的位置是从0开始的

Solution 1 (TLE)

 class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
int n = numbers.size();
for (int i = ; i < n; i++) {
for (int j = i + ; j < n; j++) {
if (numbers[i] + numbers[j] == target) {
result.push_back(i);
result.push_back(j);
}
}
}
return result;
}
};

  那怎样才能降低时间复杂度呢?这里有个经验准则,数组及字符串问题往往与(unordered)map、(unordered)set有关。这里使用unordered_map,用于查找;首先想到的思路是先遍历一遍数组,建立map映射表(元素值和位置的映射),然后再遍历一遍查找与当前元素之和为目标值的元素。建立m(数组元素)与m的位置的映射。

Solution 2

 class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> m;
int n = nums.size();
vector<int> result;
for (int i = ; i < n; ++i) {
m[nums[i]] = i;
}
for (int i = ; i < n; ++i) {
int t = target - nums[i];
//m.find(t) != m.end() 可以用 m.count(t)代替
       //you may not use the same element twice.
if (m.find(t) != m.end() && m[t] != i) {
result.push_back(i);
result.push_back(m[t]);
break;
}
}
return result;
}
};

  有一种优化方法,思路是从数组头开始,依次将元素对应的加数加入map中,在建立映射的过程中,若发现map中已经存在了一个元素,由于这个元素的存在是之前的操作才加入到map中,及此元素对应的加数在之前已经存在,故直接返回即可。题设 each input would have exactly one solution。建立target-m与m的位置的映射。

Solution 3

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

【LeetCode】001. TwoSum的更多相关文章

  1. 【LeetCode】001. Two Sum

    题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...

  2. 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

    [LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...

  3. 【Leetcode】Pascal&#39;s Triangle II

    Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3 ...

  4. 53. Maximum Subarray【leetcode】

    53. Maximum Subarray[leetcode] Find the contiguous subarray within an array (containing at least one ...

  5. 27. Remove Element【leetcode】

    27. Remove Element[leetcode] Given an array and a value, remove all instances of that value in place ...

  6. 【刷题】【LeetCode】007-整数反转-easy

    [刷题][LeetCode]总 用动画的形式呈现解LeetCode题目的思路 参考链接-空 007-整数反转 方法: 弹出和推入数字 & 溢出前进行检查 思路: 我们可以一次构建反转整数的一位 ...

  7. 【刷题】【LeetCode】000-十大经典排序算法

    [刷题][LeetCode]总 用动画的形式呈现解LeetCode题目的思路 参考链接 000-十大经典排序算法

  8. 【leetcode】893. Groups of Special-Equivalent Strings

    Algorithm [leetcode]893. Groups of Special-Equivalent Strings https://leetcode.com/problems/groups-o ...

  9. 【leetcode】657. Robot Return to Origin

    Algorithm [leetcode]657. Robot Return to Origin https://leetcode.com/problems/robot-return-to-origin ...

随机推荐

  1. 一个由自增运算符以及C语法顺序细节引起的bug

     一.问题描述 在编写modbus代码时发生一件由语法细节引起的bug,起因是自增运算符以及C语法顺序. 输入的数据是2233=0X08B9,高低字节顺序是0x08 0xB9, 使用modbus po ...

  2. Laravel 学习笔记之 Composer 自动加载

    说明:本文主要以Laravel的容器类Container为例做简单说明Composer的自动加载机制. Composer的自动加载机制 1.初始化一个composer项目 在一个空目录下compose ...

  3. 常用模块---sys&logging&序列化模块(json&pickle)

    sys 模块 sys.argv 命令行参数List,第一个元素是程序本身路径,通常用来避免io 阻塞 print('欢迎进入') info=sys.argv ': print('login succe ...

  4. Docker容器技术-在开发中引用Docker

    明确一点: 容器不适合构建那种发布周期以周或月为单位的大型单一架构企业软件,容器适合采用微服务的方式,以及探索诸如持续部署这样的技术,使得我们能安全地在一天内多次更新生产环境. 一.在开发中引用Doc ...

  5. pearson相关分析在R中的实现

    三个相关性函数: cor():R自带的,输入数据可以是vector,matrix,data.frame,输出两两的相关系数R值 cor.test():R自带的,输入数据只能是两个vector,输出两个 ...

  6. awk中打印连续多列,或者删除多列的技巧

    问题:比如有一个文件是20列,你只要后面的18列,怎么打印. 方法:把第一列和第二列做空:用print打印 [wangjq@mgmt humandb]$ cat test 1 2 3 4 5 6 7 ...

  7. codeforces 155D 质数

    题意:有编号1到n的n台机器,有m次操作,操作为开启或关闭机器,成功开启机器k的条件为k和所有已经开启的机器编号互质. 思路:vis[i]数组存放占领i这个位置的机器编号,因为所有开启的机器的编号互质 ...

  8. mongodb的使用(入门)

    1.登录mongodb ./bin/mongo 2.查看所有数据库 show dbs  ##默认有admin  和  local两个库 3.创建数据库 use test #创建数据库后,如果不写入数据 ...

  9. C#反射第一天

    [转]C#反射   反射(Reflection)是.NET中的重要机制,通过放射,可以在运行时获得.NET中每一个类型(包括类.结构.委托.接口和枚举等)的成员,包括方法.属性.事件,以及构造函数等. ...

  10. Python之爬虫总结

    一.爬虫之requests a.介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3)     b.注意:re ...