两数之和 [ leetcode ]
原题地址: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 ]的更多相关文章
- [Java]1.两数之和 - LeetCode
1 题目 2 思路与代码 思路一:暴力法(两层For循环) 时间复杂度:O(n^2) 对于每个元素,我们试图通过遍历数组的其余部分来寻找它所对应的目标元素,这将耗费 O(n) 的时间.因此时间复杂度为 ...
- 1. 两数之和 LeetCode
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums = [, , , ], target = 因为 n ...
- 两数之和LeetCode
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数组中同样的元 ...
- LeetCode 170. Two Sum III - Data structure design (两数之和之三 - 数据结构设计)$
Design and implement a TwoSum class. It should support the following operations: add and find. add - ...
- 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 ...
- 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 ...
- [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 ...
- [LeetCode] 1. Two Sum 两数之和
Part 1. 题目描述 (easy) Given an array of integers, return indices of the two numbers such that they add ...
- 两数之和,两数相加(leetcode)
我们都知道算法是程序员成长重要的一环,怎么才能提高算法呢, 出来在网上看视频之外,动手练习是非常重要的.leetcode 就是一个非常好的锻炼平台. 1. 两数之和,在 leetcode 里面是属于 ...
随机推荐
- HM16.0帧内预测重要函数笔记
Void TEncSearch::estIntraPredQT 亮度块的帧内预测入口函数 Void TComPrediction::initAdiPatternChType 获取参考样本点并滤波 ...
- grunt in webstorm
1.install grunt sudo npm install -g grunt-cli npm install grunt --save-dev
- Hive 函数之内置运算符
本章介绍Hive的内置运算符.在Hive有四种类型的运算符: 关系运算符 算术运算符 逻辑运算符 复杂运算符 关系运算符 这些操作符被用来比较两个操作数.下表描述了在Hive中可用的关系运算符: 运算 ...
- JAVA大作业汇总3
JAVA大作业3 代码 ``` package thegreatwork; import java.util.; import java.io.; /Board.java 目的:里面有一些关于如何移动 ...
- jmeter3.2版本如何进行webservice接口功能测试
jmeter3.2版本之后就没有SOAP/XML-RPC Request插件了,所以没办法直接进行webservice接口的测试. 原理上: Web service一般就是用SOAP协议通过HTTP来 ...
- Ubuntu下使用Git_6
这回真的是最后一篇了,哈哈,改写提交. 这里这部分在目前的学习阶段还没有用到,所以,这里将不在有实验的部分,在下面的链接中有详细的介绍 这也是我第一讲一个网站的内容完成的学习完成,这这部分,我讲简单的 ...
- 【转】ASP.NET Core 快速入门(环境篇)
原文链接:http://www.cnblogs.com/zhaopei/p/netcore.html [申明]:本人.NET Core小白.Linux小白.MySql小白.nginx小白.而今天要说是 ...
- 多版本python import 问题解决方案
原文http://www.tuicool.com/articles/EnE7nm6 多版本Python共存[支持使用pip安装包] 有时特殊需要会要用到高版本的Python, 但是系统自带的版本又是很 ...
- LeetCode 81——搜索旋转排序数组 II
1. 题目 2. 解答 2.1. 方法一 基于 LeetCode 33--搜索旋转排序数组 中的方法二. 当 nums[mid] = nums[right] 时,比如 [1, 1, 2, 1, 1], ...
- Java 多态方法构造器执行方法
我们参考下面这个例子: 读者可以提前考虑一下,这段程序的输出会是什么. public class Polymorphism { /** * 创建一个类A * 该类中有一个方法draw,以及一个构造方法 ...