原题地址:https://leetcode-cn.com/articles/two-sum/

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

以上是原题


本题得出正确答案非常简单,但显然题目的意图不仅仅是得到答案,而是以更好的方式得出答案。

先来看常规思路:

  无脑循环法:

  两层循环嵌套,依次相加数组元素,和等于目标值,则返回两个循环的下标,代码如下:

     public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (target == nums[i] + nums[j]) {
return new int[]{i, j};
}
}
}
return null;
}

  时间复杂度:O(n2)  

  哈希法:

  利用哈希表存储数组元素与下标的对应关系,通过一定的空间代价来换取更少的时间消耗,给出代码:

     public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int c = target - nums[i];
Integer t = map.get(c);
if (t != null && t != i) { // t != i 排除同一个元素被利用两次的情况
return new int[]{map.get(target - nums[i]), i};
}
}
return null;
}

  先将数组元素与其下标的对应关系存入hashmap中,在遍历数组元素,用目标值减去数组元素,如果在hashmap中能通过差值取到对应的元素,则说明该元素与差值为题目中要求得的结果。为什么要判断 (t != i)呢?这里有一种特殊情况,例如 [2, 3, 1]的数组,target=4,那么map中的值为{2 : 0, 3 :1, 1 : 2}, 在第一次循环中 nums[0] = 2, target - nums[0] = 2, map.get(nums[0]) 能取到对应的值2,返回结果[ map.get(nums[0]), nums[0] ] 也就是[0, 0],正确的结果应为[1, 2].

  采用hash法,时间复杂度为O(n).

  改解法可进一步优化为一次循环:

     public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int c = target - nums[i];
Integer t = map.get(c);
if(t != null) {
return new int[]{map.get(target - nums[i]), i};
}
map.put(nums[i], i);
}
return null;
}

  这里重点要注意第9行的map.put(nums[i], i) 要写在map.get(c)语句之后,原因与上段代码判断(t != i)相同。

两数之和 [ leetcode ]的更多相关文章

  1. [Java]1.两数之和 - LeetCode

    1 题目 2 思路与代码 思路一:暴力法(两层For循环) 时间复杂度:O(n^2) 对于每个元素,我们试图通过遍历数组的其余部分来寻找它所对应的目标元素,这将耗费 O(n) 的时间.因此时间复杂度为 ...

  2. 1. 两数之和 LeetCode

    给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums = [, , , ], target = 因为 n ...

  3. 两数之和LeetCode

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数组中同样的元 ...

  4. LeetCode 170. Two Sum III - Data structure design (两数之和之三 - 数据结构设计)$

    Design and implement a TwoSum class. It should support the following operations: add and find. add - ...

  5. LeetCode 371. Sum of Two Integers (两数之和)

    Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Exam ...

  6. LeetCode 167. Two Sum II - Input array is sorted (两数之和之二 - 输入的是有序数组)

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

  7. [LeetCode] Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树

    Given a Binary Search Tree and a target number, return true if there exist two elements in the BST s ...

  8. [LeetCode] 1. Two Sum 两数之和

    Part 1. 题目描述 (easy) Given an array of integers, return indices of the two numbers such that they add ...

  9. 两数之和,两数相加(leetcode)

    我们都知道算法是程序员成长重要的一环,怎么才能提高算法呢, 出来在网上看视频之外,动手练习是非常重要的.leetcode 就是一个非常好的锻炼平台. 1. 两数之和,在 leetcode 里面是属于 ...

随机推荐

  1. Educational Codeforces Round 47 (Rated for Div. 2) :C. Annoying Present(等差求和)

    题目链接:http://codeforces.com/contest/1009/problem/C 解题心得: 题意就是一个初始全为0长度为n的数列,m此操作,每次给你两个数x.d,你需要在数列中选一 ...

  2. fastDFS 上传 java源码

    要想搭建fastDFS网上有相近的文章: 分布式文件系统 - FastDFS 在 CentOS 下配置安装部署 分布式文件系统 - FastDFS 配置 Nginx 模块及上传测试 首先下载fastd ...

  3. 基于Ubuntu Server 16.04 LTS版本安装和部署Django之(五):测试项目

    基于Ubuntu Server 16.04 LTS版本安装和部署Django之(一):安装Python3-pip和Django 基于Ubuntu Server 16.04 LTS版本安装和部署Djan ...

  4. struts2官方 中文教程 系列六:表单验证

    先贴个本帖的地址,以免被爬:struts2教程 官方系列六:表单验证  即 http://www.cnblogs.com/linghaoxinpian/p/6906720.html 下载本章节代码 介 ...

  5. MyEclipse10安装checkStyle与findBugs插件--详细完美结局-费元星

    本人QQ:971751392(屌丝一枚) Myeclipse10安装checkStyle与findBugs插件详细完美结局方案: 资源一: http://download.csdn.net/detai ...

  6. 在spring+beranate中多数据源中使用 ThreadLocal ,总结的原理 --费元星

    设计模式 首先,ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问 ...

  7. 让Dreamweaver支持cshtml (MVC Razor环境)

    介绍:让Dreamweaver支持cshtml 正文: 如题,刚才搜了很久,都搜不到答案,幸好得到“包大人”(同事)的帮助,才得以解决. DW支持很多文件类型的代码提示,可是类型太多,不可能全部都有, ...

  8. redis学习资料汇总

    redis学习资料汇总 2017年01月07日 22:10:37 阅读数:281 转载:http://blog.csdn.net/wtyvhreal/article/details/50427627 ...

  9. 菜鸟级appium 必看

    之所以写这个,因为太多新人,appium环境半天都搭建不好,版本问题,兼容问题等等. 自己的解决方案:1 官网下载nodejs,建议安装长期支持版 2 进入appium官网,点击下载,跳转到githu ...

  10. 剑指offer-斐波那契数列07

    题目描述 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0). n<=39 class Solution: def Fibonacci(self ...