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. android开发 如何通过web服务器访问MYSQL数据库并且使其数据同步到android SQLite数据库?

    通过web服务器访问MYSQL数据库有以下几个过程: 1.在MySql下创建自己的数据库和自己的表单 2.连接数据库. 3.访问数据库 1.创建web工程 (服务器端) 在Myeclipse下新建一个 ...

  2. 2013 蓝桥杯校内选拔赛 java本科B组(题目+答案)

    一.标题:正则表示     正则表达式表示了串的某种规则或规律.恰当地使用正则表达式,可以使得代码简洁.事半功倍.java的很多API都支持正则表达式作为参数.其中的String.split就是这样. ...

  3. HDU1548(楼梯问题bfs)

    #include"cstdio" #include"queue" #include"cstring" using namespace std ...

  4. PhpStorm选中相同文字高亮

    1.Setting(设置)->plugins->Browse Repositories 输入BrowseWordAtCaret 搜索,安装,然后重启: 2.Setting(设置) -> ...

  5. 03_android日志猫的使用

    在java基础的时候如果想调试程序打一下日志,用的是System.out.println();. 控制台输出的其实不是咱们的日志,而是我把整个项目的部署到设备上.控制台输出的是这个东西.Uploadi ...

  6. HTML5新增的结构元素

    HTML5的结构 一:新增的主体结构元素 在HTML5中,为了使文档的结构更加清晰明确,追加了几个与页眉,页脚内容区块等文档结构相关联的结构元素. 1.1article元素 article元素代表文档 ...

  7. PCL 不同类型的点云之间进行类型转换

    PCL 不同类型的点云之间进行类型转换 可以使用PCL里面现成的函数pcl::copyPointCloud(): #include <pcl/common/impl/io.h> pcl:: ...

  8. p2661 信息传递(Tarjan模板)

    传送门 题目 有 nnn 个同学(编号为 111 到 nnn )正在玩一个信息传递的游戏.在游戏里每人都有一个固定的信息传递对象,其中,编号为 iii 的同学的信息传递对象是编号为 TiT_iTi​ ...

  9. python+selenium UI自动化不同浏览器之间的切换

    class register(): ROBOT_LIBRARY_SCOPE = 'GLOBAL' def __init__(self): pass # m默认打开chrome def open_bro ...

  10. Tomcat 如何部署多个应用

    Tomcat 如何部署多个应用 https://blog.csdn.net/tdcqfyl/article/details/51966387