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 ...
随机推荐
- SQL中replace函数
string sql1 = "select price from dbo.eazy_farm where REPLACE(title,' ','')='" + cainame + ...
- k8s 基础(4) k8s安装
转自 http://www.cnblogs.com/informatics/p/7389806.html 安装和配置 从github.com/kubernetes/kubernetes上下载1.6.8 ...
- 关于Android项目中,突然就R类找不到已存在的资源文件的解决方法
项目代码早上打开正常,下午开的时候突然提示R类找不到已存在的布局文件,于是试了各种方法,CLEAN啊,重启啊,均无效,然后去网上搜了下,遇到这个问题的人还不少. 看到其中有这么一条解决方法,删除导入的 ...
- WM学习之——火山
效果图 节点图如下: 说明: Radial grad--锥形建立节点 Perlin Noise--基础地形创建节点 Combiner--联合节点 Clamp--范围/高度控制节点 Bias/Gain- ...
- C++类和对象的一个简单的实例
题目:找出一个整形数组中的元素的最大值 下面,我们用类和对象的方法来做. #include<iostream> using namespace std; class Array_max{ ...
- Angular07 路由的工作流程、路由参数、子路由、利用路由加载模块、模块懒加载???
1 Angular路由的工作流程 用户在浏览器输入一个URL -> Angular将获取到这个URL并将其解析成一个UrlTree实例 -> Angular会到路由配置中去寻找并激活与Ur ...
- 树莓派 Learning 002 装机后必要的操作 --- 08 实现PC端 远程登入 树莓派 --- 法2 远程登录树莓派的图形桌面
树莓派 装机后必要的操作 - 实现PC端 远程登入 树莓派 我的树莓派型号:Raspberry Pi 2 Model B V1.1 装机系统:NOOBS v1.9.2 PC端系统:win10 x64 ...
- p2661 信息传递(Tarjan模板)
传送门 题目 有 nnn 个同学(编号为 111 到 nnn )正在玩一个信息传递的游戏.在游戏里每人都有一个固定的信息传递对象,其中,编号为 iii 的同学的信息传递对象是编号为 TiT_iTi ...
- 8、scala函数式编程
一.函数式编程1 1.介绍 Scala中的函数是Java中完全没有的概念.因为Java是完全面向对象的编程语言,没有任何面向过程编程语言的特性,因此Java中的一等公民是类和对象, 而且只有方法的概念 ...
- opencv头文件
转载自:http://blog.csdn.net/aaron121211/article/details/51526901 1. .hpp文件是.h和.cpp文件在一起的2. #include < ...