两数之和 [ 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++远征之封装篇(下)-学习笔记
C++远征之封装篇(下) c++封装概述 下半篇依然围绕类 & 对象进行展开 将原本学过的简单元素融合成复杂的新知识点. 对象 + 数据成员 = 对象成员(对象作为数据成员) 对象 + 数组 ...
- node获取URL数据
req.method -->GET req.hostname -->127.0.0.1 req.originalUrl -->/test/test/test?name=wang ...
- 贪心算法之Kruskal
克鲁斯卡尔Kruskal算法同Prim算法一样,都是求最小生成树.Kruskal是不断的找最短边,加入集合,且不构成回路. 所以,我们可以给每个点定义一个集合,一边的起点和终点查看是否属于同一集合,如 ...
- octave简易操作
语言以分号;结尾if for while等语句后用,来承接关系if ,elseif ,else ,end;for i=1:10,end;while a>3 ,end; while true, ...
- java性能测试工具 jprofiler
1.下载地址 官方网址:http://www.ej-technologies.com/products/jprofiler/overview.html 2.Eclipse集成 该文(http://ji ...
- Plsql developer 怎么在打开时登陆配置oracel client?
配置前 logon 这块是空白的,该怎么配置呢? 看下面 --> 安装完plsql 后 需要安装 oracle client, 这里不再赘述,请自行百度.下面将贴出如何使用 oracle cli ...
- 1176: [Balkan2007]Mokia
1176: [Balkan2007]Mokia 链接 分析 三维偏序问题,CDQ分治论文题. 代码 #include<bits/stdc++.h> using namespace std; ...
- CentOS7安装Oracle 11gR2 图文详解
注:Oracle11gR2 X64安装 一.环境准备 安装包: 1.VMware-workstation-full-11.1.0-2496824.exe 2.CentOS-7-x86_64-DVD-1 ...
- 【连载】Bootstrap开发漂亮的前端界面之插件开发
相关文章: 1.<教你用Bootstrap开发漂亮的前端界面> 2.<Bootstrap开发漂亮的前端界面之实现原理> 3.<Bootstrap开发漂亮的前端界面之自定义 ...
- jmeter处理响应结果中文乱码
1. 在线程下面添加后置处理器BeanShell PostProcessor,增加script:prev.setDataEncoding("UTF-8"); 2. 在jmeter. ...