Two Sum【LeetCode】
来源:互联网 发布:软件下载页面打不开 编辑:程序博客网 时间:2024/06/10 08:06
题目大意:利用哈希表查找指定数的两个加数因子。
最开始一想到的是暴利遍历查找,嵌套for循环,时间复杂度太高,submit之后直接说timeout了,之后点开tag发现要求用哈希表来写,果断尝试之,因为很久没碰哈希表了,磕磕绊绊还是最终提交成功。
要运用哈希表来查询,有几个问题需要解决:
- hash(key) = key 设计一个哈希函数,用什么来作为key来创建这个哈希表
- 创建之后,又以什么形式来遍历表(如何查找)
关于查找方法,又因为题目是两数相加的和,举个例子,如果现在已知一个加数,和也已知,那么另一个加数也算是已知了的(和-加数=另一个加数),虽然另一个加数未必在提供的数组里面,但是现在是不知道的,所以就要进行查找了,直接用相减得到的另一个加数作为key去查找。
好了,看代码吧
import java.util.HashMap;import java.util.Map;/** * @question * Given an array of integers, find two numbers such that they add up to a specific target number.The function twoSum should return indices of the two numbers such that they add up to the targetwhere index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.You may assume that each input would have exactly one solution. * @example * Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2 * @author HarryGuo *@solution *1. use index of every element as the hash key and push every element into hash map *2. use target-numbers[i] as the search function to search the other add number */public class TwoSum { public static int[] twosum_1(int[] numbers, int target){int[] result = new int[2];Map<Integer , Integer > hashmap = new HashMap<Integer, Integer>();//把index作为键值,按照此键值进行构造hashmapfor(int i = 0; i < numbers.length; i++){hashmap.put(numbers[i], i);}for(int i = 0; i < numbers.length; i++){int otherAddNumber = target - numbers[i]; //潜在的另一加数if(hashmap.get(otherAddNumber)!= null && hashmap.get(otherAddNumber)!= i){//利用hashmap.get(Object key),查找另一加数,另外防止4=2+2类似的情况result[0] = i+1;result[1] = hashmap.get(otherAddNumber) + 1;break;}}return result;}public static void main(String[] args){int [] numbers = {-3,3,4,90};int target = 0;int [] result = twosum_1(numbers, target);for (int i = 0; i < result.length; i++) {System.out.println(result[i]);}}}
0 0
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- 树的括号表示+树的孩子表示线性结构实现
- 机器学习十大算法的每个算法的核心思想、工作原理、适用情况及优缺点
- 1063. Set Similarity (25)
- installshield打包成只有setup.exe的安装包时获取setup.exe所在路径的方法
- 杭电2629
- Two Sum【LeetCode】
- uva11181(概率)
- Drainage Ditches ( ISAP+GAP优化)
- 关于Staruml与powerdesigner启动使用中的问题
- Python upper() 函数 转换为大写字母
- iOS--异步加载图片的ImageView和Button
- hdu 1058 dp解法
- Acm寒假训练有感
- Winform第二天总结