Two Sum【LeetCode】

来源:互联网 发布:软件下载页面打不开 编辑:程序博客网 时间:2024/06/10 08:06

题目大意:利用哈希表查找指定数的两个加数因子。

最开始一想到的是暴利遍历查找,嵌套for循环,时间复杂度太高,submit之后直接说timeout了,之后点开tag发现要求用哈希表来写,果断尝试之,因为很久没碰哈希表了,磕磕绊绊还是最终提交成功。

要运用哈希表来查询,有几个问题需要解决:

  1. hash(key) = key   设计一个哈希函数,用什么来作为key来创建这个哈希表
  2. 创建之后,又以什么形式来遍历表(如何查找)
由于题目给的是一串整型数组,偷个懒,直接用index来作为键值创建哈希表。也可以用其他的办法,只是对于这种简单数据,还是偷懒好了偷笑

关于查找方法,又因为题目是两数相加的和,举个例子,如果现在已知一个加数,和也已知,那么另一个加数也算是已知了的(和-加数=另一个加数),虽然另一个加数未必在提供的数组里面,但是现在是不知道的,所以就要进行查找了,直接用相减得到的另一个加数作为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