leetcode hashmap
187. Repeated DNA Sequences
求重复的DNA序列
public List<String> findRepeatedDnaSequences(String s) {
Set seen = new HashSet(), repeated = new HashSet();
for (int i = 0; i + 9 < s.length(); i++) {
String ten = s.substring(i, i + 10);
if (!seen.add(ten))
repeated.add(ten);
}
return new ArrayList(repeated);
}
hashset !seen.add(ten) 添加失败返回false
299 Bulls and Cows
有一个四位数字,你猜一个结果,然后根据你猜的结果和真实结果做对比,提示有多少个数字和位置都正确的叫做bulls,还提示有多少数字正确但位置不对的叫做cows,根据这些信息来引导我们继续猜测正确的数字。这道题并没有让我们实现整个游戏,而只用实现一次比较即可。给出两个字符串,让我们找出分别几个bulls和cows。这题需要用哈希表,来建立数字和其出现次数的映射。我最开始想的方法是用两次遍历,第一次遍历找出所有位置相同且值相同的数字,即bulls,并且记录secret中不是bulls的数字出现的次数。然后第二次遍历我们针对guess中不是bulls的位置,如果在哈希表中存在,cows自增1,然后映射值减1,参见如下代码:
class Solution {
public:
string getHint(string secret, string guess) {
int m[256] = {0}, bulls = 0, cows = 0;
for (int i = 0; i < secret.size(); ++i) {
if (secret[i] == guess[i]) ++bulls;
else ++m[secret[i]];
}
for (int i = 0; i < secret.size(); ++i) {
if (secret[i] != guess[i] && m[guess[i]]) {
++cows;
--m[guess[i]];
}
}
return to_string(bulls) + "A" + to_string(cows) + "B";
}
};
我们其实可以用一次循环就搞定的,在处理不是bulls的位置时,我们看如果secret当前位置数字的映射值小于0,则表示其在guess中出现过,cows自增1,然后映射值加1,如果guess当前位置的数字的映射值大于0,则表示其在secret中出现过,cows自增1,然后映射值减1,参见代码如下:
public String getHint(String secret, String guess) {
int bulls = 0;
int cows = 0;
int[] numbers = new int[10];
for (int i = 0; i<secret.length(); i++) {
int s = Character.getNumericValue(secret.charAt(i));
int g = Character.getNumericValue(guess.charAt(i));
if (s == g) bulls++;
else {
if (numbers[s] < 0) cows++;
if (numbers[g] > 0) cows++;
numbers[s] ++;
numbers[g] --;
}
}
return bulls + "A" + cows + "B";
}
49. Group Anagrams
hashmap操作
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs == null || strs.length == 0) return new ArrayList<List<String>>();
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String s : strs) {
char[] ca = s.toCharArray();
Arrays.sort(ca);
String keyStr = String.valueOf(ca);
if (!map.containsKey(keyStr)) map.put(keyStr, new ArrayList<String>());
map.get(keyStr).add(s);
}
return new ArrayList<List<String>>(map.values());
}
}
743. Network Delay Time
- Use Map<Integer, Map<Integer, Integer>> to store the source node, target node and the distance between them.
- Offer the node K to a PriorityQueue.
- Then keep getting the closest nodes to the current node and calculate the distance from the source (K) to this node (absolute distance). Use a Map to store the shortest absolute distance of each node.
- Return the node with the largest absolute distance.
public int networkDelayTime(int[][] times, int N, int K) {
if(times == null || times.length == 0){
return -1;
}
// store the source node as key. The value is another map of the neighbor nodes and distance.
Map<Integer, Map<Integer, Integer>> path = new HashMap<>();
for(int[] time : times){
Map<Integer, Integer> sourceMap = path.get(time[0]);
if(sourceMap == null){
sourceMap = new HashMap<>();
path.put(time[0], sourceMap);
}
Integer dis = sourceMap.get(time[1]);
if(dis == null || dis > time[2]){
sourceMap.put(time[1], time[2]);
} } //Use PriorityQueue to get the node with shortest absolute distance
//and calculate the absolute distance of its neighbor nodes.
Map<Integer, Integer> distanceMap = new HashMap<>();
distanceMap.put(K, 0);
PriorityQueue<int[]> pq = new PriorityQueue<>((i1, i2) -> {return i1[1] - i2[1];});
pq.offer(new int[]{K, 0});
int max = -1;
while(!pq.isEmpty()){
int[] cur = pq.poll();
int node = cur[0];
int distance = cur[1]; // Ignore processed nodes
if(distanceMap.containsKey(node) && distanceMap.get(node) < distance){
continue;
} Map<Integer, Integer> sourceMap = path.get(node);
if(sourceMap == null){
continue;
}
for(Map.Entry<Integer, Integer> entry : sourceMap.entrySet()){
int absoluteDistence = distance + entry.getValue();
int targetNode = entry.getKey();
if(distanceMap.containsKey(targetNode) && distanceMap.get(targetNode) <= absoluteDistence){
continue;
}
distanceMap.put(targetNode, absoluteDistence);
pq.offer(new int[]{targetNode, absoluteDistence});
}
}
// get the largest absolute distance.
for(int val : distanceMap.values()){
if(val > max){
max = val;
}
}
return distanceMap.size() == N ? max : -1;
}
leetcode hashmap的更多相关文章
- leetcode@ [336] Palindrome Pairs (HashMap)
https://leetcode.com/problems/palindrome-pairs/ Given a list of unique words. Find all pairs of dist ...
- LeetCode算法题-Design HashMap(Java实现)
这是悦乐书的第299次更新,第318篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第167题(顺位题号是706).在不使用任何内置哈希表库的情况下设计HashMap.具体 ...
- [LeetCode] Design HashMap 设计HashMap
Design a HashMap without using any built-in hash table libraries. To be specific, your design should ...
- LeetCode:用HashMap解决问题
LeetCode:用HashMap解决问题 Find Anagram Mappings class Solution { public int[] anagramMappings(int[] A, i ...
- LeetCode 706. Design HashMap (设计哈希映射)
题目标签:HashMap 题目让我们设计一个 hashmap, 有put, get, remove 功能. 建立一个 int array, index 是key, 值是 value,具体看code. ...
- 【LeetCode】缺失的第一个正数【原地HashMap】
给定一个未排序的整数数组,找出其中没有出现的最小的正整数. 示例 1: 输入: [1,2,0] 输出: 3 示例 2: 输入: [3,4,-1,1] 输出: 2 示例 3: 输入: [7,8,9,11 ...
- 【LeetCode】706. Design HashMap 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- LeetCode 706 Design HashMap 解题报告
题目要求 Design a HashMap without using any built-in hash table libraries. To be specific, your design s ...
- [LeetCode&Python] Problem 706. Design HashMap
Design a HashMap without using any built-in hash table libraries. To be specific, your design should ...
随机推荐
- runtime查找 UIAlertAction 的key 及 UIActionSheet 设置字体颜色
修改不了颜色了 结果发现kvo 的key 不对 哎 直接上代码 设置正确的属性找到对应的key 还以为iOS 11改变了方法 unsigned int count; Ivar *ivars = c ...
- 安装redis-3.2.10单节点
前段时间安装好的redis,今天用脚本安装的时候突然出现版本异常的问题,所以更新一篇为大家提供参考 本次安装在CentOS6.5,采用的redis-3.2.10,最新的redis-4.0.1安装同样适 ...
- Android 编程 AMapLocationClientOption 类中的 setNeedAddress 方法用处 (高德地图 com.amap.api.location.AMapLocationClientOption 中的类)
最近在用高德地图来写Android App, 其中有一些 方法是不太理解的,这里写一下 对 高德地图 com.amap.api.location.AMapLocationClientOption ...
- BZOJ2687 交与并/BZOJ2369 区间【决策单调性优化DP】【分治】
Description 对于一个区间集合 {A1,A2--Ak}(K>1,Ai不等于Aj(i不等于J),定义其权值 S=|A1∪A2∪--AK|*|A1∩A2--∩Ak| 即它们的交区间的长度乘 ...
- MAC OS环境下搭建基于Python语言的appium自动化测试环境
#1 安装JDK java -version #2 下载SDK http://adt.android-studio.org/ 下载adt #3 配置sdk环境变量 打开终端,依次输入命令 vim .b ...
- eclipse 无用代码扫描工具UCDetector
本文主要介绍UCDetector(无用代码扫描工具)使用方法及局限 对于沉积或多方接手开发的项目经常会遇到一坨一坨无用的代码,但一个一个类查找又相当费时,这里介绍一个eclipse插件扫描没有引用的类 ...
- wpf 动态得到label的宽度(无刷新情况)
var l =newLabel(){Content="Hello"}; l.Measure(newSize(double.PositiveInfinity,double.Posit ...
- 构建docker私有库
前提: ip: 172.16.0.9 docker: Version: 18.05.0-ce 1下载registry docker pull registry 2 建库 将库像 ...
- bzoj1002 [FJOI2007]轮状病毒——找规律+高精度
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1002 打表找规律,似乎是这样:https://blog.csdn.net/fzhvampir ...
- BZOJ2384:[CEOI2014]Match
浅谈\(KMP\):https://www.cnblogs.com/AKMer/p/10438148.html 题目传送门:https://lydsy.com/JudgeOnline/problem. ...