哈希
1. 两数之和
java
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> mp = new HashMap<>();
int[] ans = new int[2];
for (int i = 0; i < nums.length; i++) {
if (mp.containsKey(target - nums[i])) {
ans[0] = mp.get(target - nums[i]);
ans[1] = i;
break;
}
mp.put(nums[i], i);
}
return ans;
}
}49. 字母异位词分组
java
// 哈希,以字符串排序后的新字符串作为key,往map中添加该字符串
// 最后的结果可以直接new,将map.values()作为参数传递给ArrayList
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
char[] s = str.toCharArray();
Arrays.sort(s);
String key = new String(s);
List<String> strList = map.getOrDefault(key, new ArrayList<String>());
strList.add(str);
map.put(key, strList);
}
return new ArrayList<>(map.values());
}
}128. 最长连续序列
java
// 第一次遍历nums加入set
// 第二次遍历set,无前驱的统计
class Solution {
public int longestConsecutive(int[] nums) {
int ans = 0;
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
for (int num : set) {
if (!set.contains(num - 1)) {
int cur = 1;
while (set.contains(++num)) {
cur++;
}
ans = Math.max(ans, cur);
}
}
return ans;
}
}