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学习笔记】 点击穿透(Click Through)

    问题:开发一个App,主界面用了Activity,子页面用了Fragment.从Activity跳转到Fragment后Fragment透明,并且点击击穿到Axtivity. 分析:刚开始没有注意到点 ...

  2. Azure Public IP DNS域名

    在某些环境下,PIP是Azure上的一种比较好的解决方案处理一些特殊的环境.比如大量的端口需要打开.向外部的访问非常多等等. 但目前,Azure的Reserved IP address不用应用到PIP ...

  3. css关于内外边距的详细解释

    贴图吧,图一眼明了. 无效果时候有 只有一个<div>啦啦啦</div> 只有padding时候有: padding详细设计时: 解释:padding是对内的,如padding ...

  4. Spring MVC Flash Attribute 的讲解与使用示例

    转自:https://www.oschina.net/translate/spring-mvc-flash-attribute-example Spring MVC 3.1版本加了一个很有用的特性,F ...

  5. linux日常管理-curl工具

    curl 在linux命令行中用于访问网站,下载东西, 可以用 curl www.qq.com 访问 出现很多源代码 ///////////////////////////////////////// ...

  6. web安全之同源策略

    为什么使用同源策略?一个重要原因就是对cookie的保护,cookie 中存着sessionID .如果已经登录网站,同时又去了任意其他网站,该网站有恶意JS代码.如果没有同源策略,那么这个网站就能通 ...

  7. Java探索之旅(11)——抽象类与接口

    1.Java数据类型       ❶不可变类,是指当创建了这个类的实例后,就不允许修改它的属性值. 它包括:         Primitive变量:boolean,byte, char, doubl ...

  8. Ubuntu W: GPG 错误:下列签名无效: BADSIG 84DBCE2DCEC45805 Launchpad PPA fo

    Ubuntu12.04  安装R语言的时候出现的报错. 研究了两个晚上,解决办法如下,跟参考贴有点出入: ############################################### ...

  9. Entity Framework Code-First(9.10):DataAnnotations - NotMapped Attribute

    DataAnnotations - NotMapped Attribute: NotMapped attribute can be applied to properties of a class. ...

  10. jquery提供的数据提交方式1

    1,ajax提交,部分代码为easyui function editNode(id){ $.ajax({ dataType:'json', async:true, //默认的就是异步提交 type:' ...