两数之和 [ 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 里面是属于 ...
随机推荐
- C语言实现二分查找
二分查找优势:比顺序查找更有效率 特点:元素按顺序排列 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include ...
- 016---Django的ModelForm
对于forms组件虽然可以帮我们渲染html页面,也可以做校验,但是,保存到数据库要取各字段的值,还要手动保存.所以引入了一个新的组件 这是一个神奇的组件,通过名字我们可以看出来,这个组件的功能就是把 ...
- maven 添加自己下载的jar包到本地仓库
1.在pom文件中添加依赖,其中groupId等变量都自拟. 例如: 2.在命令行执行以下命令,提示build success即表示安装成功. mvn install:install-file -Dg ...
- 使用source命令解决mysql导入乱码问题
设定编码格式:mysql -u root -p --default-character-set=utf8 use dbname source /root/newsdata.sql
- python内置模块[re]
python内置模块[re] re模块: python的re模块(Regular Expression正则表达式)提供各种正则表达式的匹配操作,在文本解析.复杂字符串分析和信息提取时是一个非常有用的工 ...
- 掘金 Android 文章精选合集
掘金 Android 文章精选合集 掘金官方 关注 2017.07.10 16:42* 字数 175276 阅读 50053评论 13喜欢 669 用两张图告诉你,为什么你的 App 会卡顿? - A ...
- FJOI 2019 游记
(FJOI 2019 滚粗记) Day 0 早上刷了一些水题,然后就上路了. (画图3D好好玩) 来得晚只有十几分钟时间看考场,于是连试机题都没有Ak. Day 1 果然我还是太菜了 走过来的时候再讨 ...
- mvc4 Forms验证存储 两种登录代码
自己也不知道网上看到的第一种居多,第二种用到的人很少,第二种代码十分简洁,就是不清楚是否有安全隐患. 要采用Forms身份验证,先要在应用程序根目录中的Web.config中做相应的设置: <a ...
- C#操作Excel文件(转)
摘要:本文介绍了Excel对象.C#中的受管代码和非受管代码,并介绍了COM组件在.net环境中的使用. 关键词:受管代码:非受管代码:Excel对象:动态连接库 引言 Excel是微软公司办公自动化 ...
- adb 命令模拟按键事件
转自:http://blog.csdn.net/jlminghui/article/details/39268419 例子:adb shell input keyevent 4 #这条命令相当于按了设 ...