Leetcode Hot100 Hash
题号: 1、49、128
import java.util.*;
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>();
Map<String,List<String>> rec = new HashMap<>();
for (String str : strs) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
String key = new String(chars);
List<String> value = rec.getOrDefault(key,new ArrayList<>());
value.add(str);
rec.put(key,value);
}
for (List<String> value : rec.values()) {
res.add(value);
}
return res;
}
}
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> num_set = new HashSet<Integer>();
for (int num : nums) {
num_set.add(num);
}
int longestStreak = 0;
for (int num : num_set) {
if (!num_set.contains(num - 1)) {
int currentNum = num;
int currentStreak = 1;
while (num_set.contains(currentNum + 1)) {
currentNum += 1;
currentStreak += 1;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
}
return longestStreak;
}
}
收获
- MAP.getOrDefault方法
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/82b373a32e850f186a393e290b3843d5.png)
- HashSet:底层仍为HashMap,value为 PRESENT(占位符)