Two Sum【LeetCode】

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

最开始一想到的是暴利遍历查找,嵌套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 target
	where 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作为键值,按照此键值进行构造hashmap
		for(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
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值