1 Two Sum
public class Solution { public int[] twoSum(int[] nums, int target) { if (nums == null || nums.length < 2) { return null; } HashMap<Integer, Integer> hs = new HashMap<Integer, Integer>();//用HashMap for (int i = 0; i < nums.length; i++) { hs.put(nums[i], i + 1);//hashMap.put() } int[] res = new int[2]; for (int i = 0; i < nums.length; i++) { if (hs.containsKey(target - nums[i])) { int index1 = i + 1; int index2 = hs.get(target - nums[i]); if (index1 == index2) { continue; }//排除重复 res[0] = index1; res[1] = index2; return res;//得到一组答案先返回, 否则结果会倒序,比如[3,2,4] 6 应该返回[2,3],不写这句返回错误答案[3,2] } } return res; } }
HashSet与HashMap区别
参考:http://www.importnew.com/6931.html
HashSet和HashMap的区别
*HashMap* | *HashSet* |
HashMap实现了Map接口 | HashSet实现了Set接口 |
HashMap储存键值对 | HashSet仅仅存储对象 |
使用put()方法将元素放入map中 | 使用add()方法将元素放入set中 |
HashMap中使用键对象来计算hashcode值 | HashSet使用成员对象来计算hashcode值,对于两个对象来说hashcode可能相同,所以equals()方法用来判断对象的相等性,如果两个对象不同的话,那么返回false |
HashMap比较快,因为是使用唯一的键来获取对象 | HashSet较HashMap来说比较慢 |