[LeetCode] 1. Two Sum 两数之和
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].
两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> m = new HashMap<Integer,Integer>();
int[] res = new int[2];
for(int i = 0; i < nums.length; ++i)
{
m.put(nums[i],i);
}
for(int i = 0; i < nums.length; ++i)
{
int t = target - nums[i];
if(m.containsKey(t)&& m.get(t)!=i)
{
res[0] = i;
res[1] = m.get(t);
break;
}
}
return res; // 数组作为函数的返回值。
}
}
解题思路
第一天做leetcode,一次契机让我意识到我的算法超级超级差,所以开始刷题,大家都说“平生不识 TwoSum,刷尽 LeetCode
也枉然”,所以第一题就从这道题开始练习啦,努力提升自己代码能力,冲冲冲!!!
- Map.containsKey方法
判断Map集合对象中是否包含指定的键名
该方法判断Map集合对象中是否包含指定的键名。如果Map集合中包含指定的键名,则返回true,否则返回false。
语法: containsKey(Object key) - HashMap
JAVA为数据结构中的映射定义了一个接口java.util.Map,此接口主要有四个常用的实现类,分别是HashMap、Hashtable、LinkedHashMap和TreeMap
HashMap根据键的hashCode值存储数据,大多数情况下可以直接定位到它的值,因而具有很快的访问速度,但遍历顺序却是不确定的。 HashMap最多只允许一条记录的键为null,允许多条记录的值为null。HashMap非线程安全,即任一时刻可以有多个线程同时写HashMap,可能会导致数据的不一致。如果需要满足线程安全,可以用 Collections的synchronizedMap方法使HashMap具有线程安全的能力,或者使用ConcurrentHashMap。【具体看我前面写的线程方面的总结】
刚开始看到题目,就非常头脑简单的打算把所有可能的数组两数组合列出来然后相加计算, 然后发现这道题题干写了数组中同一个元素不能使用两遍,hhh所以无法暴力循环解题,采用HashMap,建立数字和其坐标位置之间的映射。先让目标数字减去一个nums[i]的数,然后看能否找到这样一个数(不能与前数相等),记录下两数坐标位置存放到res数组中,然后输出res数组即可。