两数之和
题目
思路
用map集合来存,以目标值-数组值为key,实现快速查找
代码
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (hashMap.containsKey(target - nums[i])) {
return new int[]{i, hashMap.get(target - nums[i])};
}
hashMap.put(nums[i], i);
}
return new int[0];
}
字母异位词分组
题目
思路
对字符数组中的每一个字符串进行转换,转换成字符数组并排序,保证一致
代码
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> hashMap = new HashMap<>();
for (String a : strs) {
char[] charArray = a.toCharArray();
Arrays.sort(charArray);
String str = new String(charArray);
if (hashMap.containsKey(str)) {
hashMap.get(str).add(a);
continue;
}
List<String> list = new ArrayList<>();
list.add(a);
hashMap.put(str, list);
}
List<List<String>> list = new ArrayList<>();
for (String a : hashMap.keySet()) {
list.add(hashMap.get(a));
}
return list;
}
最长连续序列
题目
思路
使用set集合来保证唯一和有序,只需要不断的判断set集合中是否含有a+1,以此来不断更新a和len,找出最大的len即可
代码
public int longestConsecutive(int[] nums) {
Set<Integer> hashSet = new HashSet<>();
for (Integer a : nums) {
hashSet.add(a);
}
int max = 0;
for (Integer a : hashSet) {
if (!hashSet.contains(a - 1)) {
int len = 1;
while (hashSet.contains(a + 1)) {
len++;
a++;
}
max = Math.max(max, len);
}
}
return max;
}
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » 力扣100题——哈希题解
发表评论 取消回复