Two Sum
Question
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
use java8 to solution
import java.util.Hashtable;
/*
* @lc app=leetcode id=1 lang=java
*
* [1] Two Sum
*/
class Solution {
public int[] twoSum(int[] nums, int target) {
Hashtable<Integer,Integer> hashtable =new Hashtable<Integer,Integer>();
int i = 0;
while ((i< nums.length)&& (hashtable.get(nums[i]) == null)){
hashtable.put(target - nums[i], i);
i++;
}
if(i<nums.length){
return new int[]{hashtable.get(nums[i]),i};
}
return null;
}
}
Next up is an understanding of Hash.
Hash :散列,通过关于键值(key)的函数,将数据映射到内存存储中一个位置来访问。这个过程叫做Hash,这个映射函数称做散列函数,存放记录的数组称做散列表(Hash Table),又叫哈希表。
hash相对于数组和链表最大的好处就是,先对数据进行分类,再进行查找,减少了遍历的过程,从而大大减少了寻值的时间。