Hash MAP/SET

Hash MAP/SET

Jason Lv3

1207. 独一无二的出现次数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public boolean uniqueOccurrences(int[] arr) {
Map<Integer, Integer> map1 = new HashMap<Integer,Integer>();
Set<Integer> set1 = new HashSet<Integer>();
for(int i = 0;i<arr.length;i++){
int count = map1.getOrDefault(arr[i],0) + 1; // 获取key对应的value,如果key不存在,则返回0,并把value设置为1
map1.put(arr[i],count);
}
// Iterator < Entry < Integer, Integer >> iterator = map1.entrySet().iterator();
// while(iterator.hasNext()){
// Entry<Integer,Integer> entry = iterator.next();
// set1.add(entry.getValue());
// }

for(Map.Entry<Integer,Integer> entry:map1.entrySet()){
set1.add(entry.getValue());
}

return map1.size()==set1.size();

}
}
HashMap五种遍历方式

49. 字母异位词分组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String,List<String>> map = new HashMap<String,List<String>>();
for(String str :strs){
char[] chars = str.toCharArray(); //将每个单词转为字符数组 排序 以此为map 的key
Arrays.sort(chars);
String kstr = new String(chars);
List<String> list = map.getOrDefault(kstr,new ArrayList<String>());
list.add(str);
map.put(kstr,list);
}
return new ArrayList<List<String>>(map.values()); //new 后面要跟 具体集合名字
}
}


128. 最长连续序列

我们要找到一个连续序列的开始 怎么才算是开始? 它的前一个不存在 因此 利用set.contains 检查是否存在 不存在就可以成为开端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
int curcount;
int longest=0;
int curnum;
for(int n:nums){
set.add(n);
}
for(int i=0;i<nums.length;i++){
if(!set.contains(nums[i]-1)){
curcount =1;
curnum=nums[i];
while(set.contains(curnum+1)){
curcount++;
curnum++;
}
longest = Math.max(longest,curcount);
}

}
return longest;
}
}
  • Title: Hash MAP/SET
  • Author: Jason
  • Created at : 2023-09-17 16:31:16
  • Updated at : 2023-09-17 17:29:18
  • Link: https://xxxijason1201.github.io/2023/09/17/LeetCode/Hash/
  • License: This work is licensed under CC BY-NC-SA 4.0.
 Comments