哈希
# 两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0; i< nums.length; i++){
int num = nums[i];
if(map.containsKey(num)){
return new int[]{i, map.get(num)};
}
map.put(target-num, i);
}
return null;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 字母的异分词
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for(int i = 0; i< strs.length; i++){
char[] c = strs[i].toCharArray();
Arrays.sort(c);
String key = new String(c);
List<String> list = map.getOrDefault(key, new ArrayList<>());
list.add(strs[i]);
map.put(key, list);
}
return new ArrayList<List<String>>(map.values());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 最长连续序列
class Solution {
public int longestConsecutive(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
Arrays.sort(nums);
Set<Integer> set = new LinkedHashSet<>();
for (int num : nums) {
set.add(num);
}
int res = 1;
int tmp =1;
int pre = Integer.MIN_VALUE;
for(int num : set){
if(num-pre == 1){
tmp++;
} else{
tmp =1;
}
pre= num;
res = Math.max(res, tmp);
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
上次更新: 2024/03/26, 9:03:00