lecture-9-hashmap
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的更多相关文章
- [C2P3] Andrew Ng - Machine Learning
##Advice for Applying Machine Learning Applying machine learning in practice is not always straightf ...
- HashMap与TreeMap源码分析
1. 引言 在红黑树--算法导论(15)中学习了红黑树的原理.本来打算自己来试着实现一下,然而在看了JDK(1.8.0)TreeMap的源码后恍然发现原来它就是利用红黑树实现的(很惭愧学了Ja ...
- HashMap的工作原理
HashMap的工作原理 HashMap的工作原理是近年来常见的Java面试题.几乎每个Java程序员都知道HashMap,都知道哪里要用HashMap,知道HashTable和HashMap之间 ...
- 计算机程序的思维逻辑 (40) - 剖析HashMap
前面两节介绍了ArrayList和LinkedList,它们的一个共同特点是,查找元素的效率都比较低,都需要逐个进行比较,本节介绍HashMap,它的查找效率则要高的多,HashMap是什么?怎么用? ...
- Java集合专题总结(1):HashMap 和 HashTable 源码学习和面试总结
2017年的秋招彻底结束了,感觉Java上面的最常见的集合相关的问题就是hash--系列和一些常用并发集合和队列,堆等结合算法一起考察,不完全统计,本人经历:先后百度.唯品会.58同城.新浪微博.趣分 ...
- 学习Redis你必须了解的数据结构——HashMap实现
本文版权归博客园和作者吴双本人共同所有,转载和爬虫请注明原文链接博客园蜗牛 cnblogs.com\tdws . 首先提供一种获取hashCode的方法,是一种比较受欢迎的方式,该方法参照了一位园友的 ...
- HashMap与HashTable的区别
HashMap和HashSet的区别是Java面试中最常被问到的问题.如果没有涉及到Collection框架以及多线程的面试,可以说是不完整.而Collection框架的问题不涉及到HashSet和H ...
- JDK1.8 HashMap 源码分析
一.概述 以键值对的形式存储,是基于Map接口的实现,可以接收null的键值,不保证有序(比如插入顺序),存储着Entry(hash, key, value, next)对象. 二.示例 public ...
- HashMap 源码解析
HashMap简介: HashMap在日常的开发中应用的非常之广泛,它是基于Hash表,实现了Map接口,以键值对(key-value)形式进行数据存储,HashMap在数据结构上使用的是数组+链表. ...
- java面试题——HashMap和Hashtable 的区别
一.HashMap 和Hashtable 的区别 我们先看2个类的定义 public class Hashtable extends Dictionary implements Map, Clonea ...
随机推荐
- Poj1258_Agri-Net(最小生成树)
一.Description(poj1258) Farmer John has been elected mayor of his town! One of his campaign promises ...
- MyEclipse 手动安装Velocity 编辑器
最近项目有使用Velocity 模板引擎,从而会用到*.VM页面!Myeclipse打开VM页面字体一片漆黑,哪有JSP那样看起来舒服(个人感觉)!为了解决这一问题就要安装Velocity编辑器,安装 ...
- 《Kubernetes权威指南第2版》学习(三)RC学习
1 RC文件介绍: kind: ReplicationController,表示是一个RC: spec.selector: RC的Pod标签(Label)选择器,监控和管理拥有这些标签的Pod实例, ...
- MATLAB模糊逻辑工具箱函数
说明:本文档中所列出的函数适用于Matlab5.3以上版本,为了简明起见,只列出了函数名,若需要进一步的说明,请参阅MATLAB的帮助文档. 1. GUI工具 Anfisedit 打开ANF ...
- python fabric的安装与使用
背景:fabric主要执行远程的shell命令,包括文件的上传.下载,以及提示用户输入等辅助其它功能. 测试系统:ubuntu16 要求:python //系统有自带,ubuntu16 通常自带pyt ...
- last 列出登入系统的用户相关信息
Linux last 命令介绍 功能说明:列出目前与过去登入系统的用户相关信息. 语法: last [-adRx][-f <记录文件>][-n <显示列数>][帐号名称. ...
- spring----IOC注解方式以及AOP
技术分析之Spring框架的IOC功能之注解的方式 Spring框架的IOC之注解方式的快速入门 1. 步骤一:导入注解开发所有需要的jar包 * 引入IOC容器必须的6个jar包 * 多引入一个:S ...
- Maven的pom实例
该pom中包含了一些我认为会需要的东西,并且加了注释.可以根据需求适当删减. 包含了spring-mvc , junit,hibernate验证,json,apache-commons组件 还有 co ...
- Spring入门第二十七课
声明式事务 直接上代码: db.properties jdbc.user=root jdbc.password=logan123 jdbc.driverClass=com.mysql.jdbc.Dri ...
- UCD9222 EN1/EN2
如果要使用UCD9222 EN1/EN2来控制每路电源的输出,那么需要注意实际是由PMBUS_CNTRL和EN1/EN2的与来控制每路的输出.
