1-leetcode1. 两数之和
注意:√
- 经典老题,用hashMap做就好了
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < n; i++) {
int need = target - nums[i];
if (hashMap.containsKey(need)){
return new int[]{i, hashMap.get(need)};
}else {
hashMap.put(nums[i], i);
}
}
return new int[]{};
}
2-leetcode49. 字母异位词分组
注意:×
- 将字符串
eat
转到char[]
中很巧妙的用到了哈希的思想 - 注意
groupAnagrams
函数中的hashMap.putIfAbsent(code, new LinkedList<>());
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> ans = new ArrayList<>();
HashMap<String, List<String>> hashMap = new HashMap<>();
for (String str : strs) {
String code = encode(str);
hashMap.putIfAbsent(code, new LinkedList<>());
hashMap.get(code).add(str);
}
for (List<String> value : hashMap.values()) {
ans.add(value);
}
return ans;
}
private String encode(String str) {
char[] code = new char[26];
for (char c : str.toCharArray()) {
int index = c - 'a';
code[index]++;
}
return new String(code);
}
3-leetcode128. 最长连续序列
注意:×
- 参考下面图片中的描述,非常好的思路(lc官方题解下面的评论中)
num-1
和后面的set.contains(curNum+1)
非常好的操作
public int longestConsecutive(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int res = 0;
for (int num : set) {
if (set.contains(num-1)){
continue;
}
int curNum = num;
int curRes = 1;
while (set.contains(curNum+1)){
curRes++;
curNum = curNum+1;
}
res = Math.max(res, curRes);
}
return res;
}