原题地址: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. linux文件操作篇 (三) 文件状态和操作属性

    #include <sys/stat.h>   int fstat(int fildes, struct stat *buf); 获取文件信息  int lstat(const char* ...

  2. go学习笔记-基础类型

    基础类型 布尔值 布尔值的类型为bool,值是true或false,默认为false. //示例代码 var isActive bool // 全局变量声明 var enabled, disabled ...

  3. Uber CEO博鳌论坛采访:看好中国市场共享经济的发展模式

    滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...

  4. MapRudecer

    MapReducer基本概念 Mapreduce是一个分布式运算程序的编程框架,是用户开发“基于hadoop的数据分析应用”的核心框架: Mapreduce核心功能是将用户编写的业务逻辑代码和自带默认 ...

  5. VI的配置

    vi下设置tab键为4个空格 在每个用户的主目录下,都有一个 vi 的配置文件".vimrc"或".exrc",没有的可以新建一个.用户可以编辑它,使这些设置在 ...

  6. java堆内存模型

     广泛地说,JVM堆内存被分为两部分——年轻代(Young Generation)和老年代(Old Generation). 年轻代 年轻代是所有新对象产生的地方.当年轻代内存空间被用完时,就会触发垃 ...

  7. Qt的index 用方法static_cast<CTableItem*>(index.internalPointer())取出来的值的成员都未初始化

    mediaData = 0x01046380 {m_Deviceid={...} m_Title={...} m_Type={...} ...} 里面是这样的值,内存已经释放,但是没有remove:

  8. 基于jersey和Apache Tomcat构建Restful Web服务(二)

    基于jersey和Apache Tomcat构建Restful Web服务(二) 上篇博客介绍了REST以及Jersey并使用其搭建了一个简单的“Hello World”,那么本次呢,再来点有趣的东西 ...

  9. [CH5302]金字塔

    题面 虽然探索金字塔是极其老套的剧情,但是有一队探险家还是到了某金字塔脚下.经过多年的研究,科学家对这座金字塔的内部结构已经有所了解.首先,金字塔由若干房间组成,房间之间连有通道.如果把房间看作节点, ...

  10. BZOJ 3809 Gty的二逼妹子序列 莫队算法+分块

    Description Autumn和Bakser又在研究Gty的妹子序列了!但他们遇到了一个难题. 对于一段妹子们,他们想让你帮忙求出这之内美丽度∈[a,b]的妹子的美丽度的种类数. 为了方便,我们 ...