本文主要是介绍哈希表题总结,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
哈希表题总结
- hot100
- 两数之和
- 字母异位词分组
- 最长连续序列
hot100
两数之和
题目链接:
1.两数之和
代码:
class Solution {public int[] twoSum(int[] nums, int target) {Map<Integer,Integer> map = new HashMap<>();int n = nums.length;for (int i = 0; i < n; i ++){if (map.containsKey(target-nums[i])){return new int[] {map.get(target - nums[i]),i};}map.put(nums[i],i );}return null;}
}
字母异位词分组
题目链接:
49.字母异位词分组
代码:
class Solution {public List<List<String>> groupAnagrams(String[] strs) {Map<String,List<String>> map = new HashMap<>();for (String str:strs){char[] array = str.toCharArray();Arrays.sort(array);String key = new String(array);List<String> list = map.getOrDefault(key, new ArrayList<String>());list.add(str);map.put(key,list);}return new ArrayList<List<String>>(map.values());}
}
最长连续序列
题目链接:
128.最长连续序列
代码:
class Solution {public int longestConsecutive(int[] nums) {Set<Integer> set = new HashSet<>();for (int i = 0; i < nums.length; i ++){set.add(nums[i]);}int len = 0;for (int s:set){if (!set.contains(s - 1)){int curr = 1;int currnum = s;while (set.contains(currnum + 1)){curr ++;currnum ++;}len = Math.max(len,curr);}}return len;}
}
这篇关于哈希表题总结的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!