1、hashmap基本操作

2、hash function,equals函数,hashCode

3、练习题

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.

1、Two pointers
2、If return the two numbers, then HashSet will be enough
3、HashMap is needed to keep the mapping from
number to index

方法一

 public int[] twoSum(int[] nums, int targer) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);//key:num[i], value:i
}
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] {i, map.get(complement)};
}
}
return result;
} public int[] twoSum(int[] nums, int targer) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);//key:num[i], value:i
}
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
result[0] = i;
result[1] = map.get(complement);
break;
}
}
return result;
}

方法二

 1 public int[] twoSum(int[] nums, int target) {
2 HashMap<Integer, Integer> map = new HashMap<>();
4 for (int i = 0; i < nums.length; i++) {
5 int complement = target - nums[i];
6 if (map.containsKey(complement && map.get(complement) != i)) {
7 return new int[] {i, map.get(complement)};
8 }
9 map.put(nums[i], i);//假设result = {1,8},在找到1时,8还没有放进去,但是找到8时,1在hashmap里面,就找到了
10 }
11 return null;
12 }

1)Word Pattern

Given a pattern and a string str, find if str follows the same
pattern. Here follow means a full match, such that there is a
bijection between a letter in pattern and a non-empty word in str.
Examples:
1. pattern = "abba", str = "dog cat cat dog" should return true.
2. pattern = "abba", str = "dog cat cat fish" should return false.
3. pattern = "aaaa", str = "dog cat cat dog" should return false.
4. pattern = "abba", str = "dog dog dog dog" should return false.
Notes:
You may assume pattern contains only lowercase letters, and str
contains lowercase letters separated by a single space.

方法一

Keep a 1:1 mapping relationship
HashMap is A->B, so two HashMaps are needed for
A <-> B
 public boolean wordPattern(String pattern, String str) {
HashMap<Character, String> map = new HaspMap<>();
HashMap<String, Character> map_reverse = new HashMap<>();
String[] words = str.split(" ");
if (pattern.length() != words.length) {//length()
return false;
}
for (int i = 0; i < pattern.length(); i++) {
char a = pattern.chatAt(i);
String b = words[i];
if (!map.containsKey(a)) {
map.put(a, b);
} else if (!map.get(a).equals(b)) {
return false;
} if (!map_reverse.containsKey(b)) {
map_reverse.put(b, a);
} else if (!map_reverse.get(b) != a) {//a is base type, can not use equals
return false;
}
}
return true;
}

方法二

Keep a 1:1 mapping relationship
HashMap is A->B, so two HashMaps are needed for A <-> B
Keep two A->B mappings at the same time
pattern -> index
string -> index

 

 public boolean worPattern(String pattern, String str) {
HashMap<Character, Integer> mapPattern = new HashMap<>();
HashMap<String, Integer> mapStr = new HashMap<>();
String[] words = str.spilt(" ");
if (patterh.length() != words.length) {
return false;
}
for (int i = 0; i < pattern.length(); i++) {
int indexP = -1;
int indexS = -1;
Character a = pattern.charAt(i);
String b = word[i];
if (mapPattern.containsKey(a)) {
indexP = mapPattern.get(a);
} else {
mapPattern.put(a, i);
} if (mapStr.containsKey(b)) {
indexS = mapStr.get(b);
} else {
mapStr.put(b, i);
}
if (indexP != indexS) {
return false;
}
}
return true;
}

方法三

 public boolean wordPattern(String pattern, String str) {
Map<Character, Integer> mappingPattern = new HashMap<>();
Map<String, Integer> mappingStr = new HashMap<>();
String[] words = str.split(" ");
if (pattern.length() != words.length) {
return false;
}
for (int i = 0; i < pattern.length(); i++) {
if (!Objects.equals(mappingPattern.put(pattern.charAt(i), i),
mappingStr.put(words[i], i))) {
return false;
}
}
return true;
}

习题三Group Anagrams

Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]

 public ArrayList<String> anagrams(String[] strs) {
HashMap<String, ArrayList<String>> mapping = new HashMap<>();
for (String str : strs) {
char[] array = str.toCharArray();
Arrays.sort(array);
String newStr = new String(array);//排序后生成一个新字符串,作为key
if (!mapping.containsKey(newStr)) {
ArrayList<String> strList = new ArrayList<>();
strList.add(str);
mapping.put(array, strList);
} else {
mapping.get(newStr).add(str);
}
}
ArrayList<String> result = new ArrayList<>();
for (String str : mapping.keySet() { result.addAll(mapping.get(str)); }
return result;
}

lecture-9-hashmap的更多相关文章

  1. [C2P3] Andrew Ng - Machine Learning

    ##Advice for Applying Machine Learning Applying machine learning in practice is not always straightf ...

  2. HashMap与TreeMap源码分析

    1. 引言     在红黑树--算法导论(15)中学习了红黑树的原理.本来打算自己来试着实现一下,然而在看了JDK(1.8.0)TreeMap的源码后恍然发现原来它就是利用红黑树实现的(很惭愧学了Ja ...

  3. HashMap的工作原理

    HashMap的工作原理   HashMap的工作原理是近年来常见的Java面试题.几乎每个Java程序员都知道HashMap,都知道哪里要用HashMap,知道HashTable和HashMap之间 ...

  4. 计算机程序的思维逻辑 (40) - 剖析HashMap

    前面两节介绍了ArrayList和LinkedList,它们的一个共同特点是,查找元素的效率都比较低,都需要逐个进行比较,本节介绍HashMap,它的查找效率则要高的多,HashMap是什么?怎么用? ...

  5. Java集合专题总结(1):HashMap 和 HashTable 源码学习和面试总结

    2017年的秋招彻底结束了,感觉Java上面的最常见的集合相关的问题就是hash--系列和一些常用并发集合和队列,堆等结合算法一起考察,不完全统计,本人经历:先后百度.唯品会.58同城.新浪微博.趣分 ...

  6. 学习Redis你必须了解的数据结构——HashMap实现

    本文版权归博客园和作者吴双本人共同所有,转载和爬虫请注明原文链接博客园蜗牛 cnblogs.com\tdws . 首先提供一种获取hashCode的方法,是一种比较受欢迎的方式,该方法参照了一位园友的 ...

  7. HashMap与HashTable的区别

    HashMap和HashSet的区别是Java面试中最常被问到的问题.如果没有涉及到Collection框架以及多线程的面试,可以说是不完整.而Collection框架的问题不涉及到HashSet和H ...

  8. JDK1.8 HashMap 源码分析

    一.概述 以键值对的形式存储,是基于Map接口的实现,可以接收null的键值,不保证有序(比如插入顺序),存储着Entry(hash, key, value, next)对象. 二.示例 public ...

  9. HashMap 源码解析

    HashMap简介: HashMap在日常的开发中应用的非常之广泛,它是基于Hash表,实现了Map接口,以键值对(key-value)形式进行数据存储,HashMap在数据结构上使用的是数组+链表. ...

  10. java面试题——HashMap和Hashtable 的区别

    一.HashMap 和Hashtable 的区别 我们先看2个类的定义 public class Hashtable extends Dictionary implements Map, Clonea ...

随机推荐

  1. RESTEasy常用注解

    一.@Path,标注资源类或方法的相对路径          Path参数的形式有三种:          1.固定值          2.纯正则表达式          3.固定值和正则表达式的混 ...

  2. eclipse如何集成tomcat插件

    刚在Eclipse官方网站下载的Eclipse,需要自己手动安装tomcat插件才能配置tomcat服务器.网上好多安装方法,这里我就不厌其烦的再写一遍,边安装边截图讲解下安装方法. 首先你要去下载E ...

  3. jQuery对象和DOM对象的互换

    Dom 对象:指的是普通的 JavaScript 对象 jQuery对象:是包装 Dom 对象后产生的对象. 一:JQuery 对象和 Dom 对象 在使用 JQuery 过程中,我们一般(也是绝大多 ...

  4. 关于Confusion Matrix

    from sklearn.metrics import confusion_matrixy_true = [2, 0, 2, 2, 0, 1]y_pred = [0, 0, 2, 2, 0, 2]pr ...

  5. J2EE 学习路线

    分享一个比较好的学习网站    http://edu.51cto.com/roadmap/view/id-86.html ================================J2EE=== ...

  6. [Uva12260]Free Goodies(dp+贪心)

    解题关键:先对p进行排序,消除p的影响,然后对w进行01背包即可.注意p对w的约束.j<=(cur+1)/2 #include<cstdio> #include<cstring ...

  7. (转)64位系统安装Delphi7提示Can’t load package:dclite70.bpl 以及 提示地址错误

    第一个问题: 今天在64的Win7上安装Delphi7,在启动时候出现如下提示: Can't load package:dclite70.bpl 告诉大家一个解决办法,就是给Delphi32.exe去 ...

  8. KickStart安装CentOS,同时安装和配置hadoop

    声明:这篇文章是前面是拾人牙慧,我是结合 http://www.111cn.net/sys/linux/59969.htm 和 http://www.cnblogs.com/mchina/p/cent ...

  9. 面试题: mysql数据库 已看1 简单的sql练习

    数据库总结--MySQL常见面试题 2015年03月24日 17:56:06 阅读数:7787 1.根据部门号从高到低,工资从低到高列出员工的信息 select * from employee ord ...

  10. 【jeasyui5】样式:调整页面显示的顶部菜单和左侧菜单

    1.顶部菜单修改:修改index2.js里面的InitTopMenu方法,将icon +2 2.左侧菜单宽度调整: 修改index.html,加上width:170的定长 <!-- 左侧菜单 - ...