力扣Hot100(Java版本)
1. 哈希
1.1 两数之和
题目描述:
-
给定一个整数数组
nums
和一个整数目标值target
,请你在该数组中找出 和为目标值target
的那 两个 整数,并返回它们的数组下标。 -
你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。
-
你可以按任意顺序返回答案。
力扣链接:
https://leetcode.cn/problems/two-sum/description/【简单】
解题思路:
-
实例化一个
HashMap
来保存<值, 索引>
-
遍历HashMap,找到就返回索引下标,找不到就添加元素
核心代码:
class Solution {public int[] twoSum(int[] nums, int target) {// map保存<值,索引>Map<Integer,Integer> map = new HashMap<>();for(int i = 0; i < nums.length; ++i){if(map.containsKey(target - nums[i])){return new int[]{map.get(target - nums[i]),i};}map.put(nums[i],i); // 返回[索引1,索引2]}return new int[0]; // 返回[]}
}
1.2 字母异位词分组
题目描述:
-
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
-
字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
力扣链接:
https://leetcode.cn/problems/group-anagrams/description【中等】
解题思路:
- Map保存
<排序后的字符串, List<String>>
- 遍历strs, 依次添加到Map
核心代码:
class Solution {public List<List<String>> groupAnagrams(String[] strs) {// 1. Map保存<排序后的str, List<String>>Map<String, List<String>> map = new HashMap<>();// 2. 遍历strs, 依次添加到Mapfor (String str : strs){char[] charStr = str.toCharArray();Arrays.sort(charStr);String orderStr = new String(charStr);if (map.containsKey(orderStr)){map.get(orderStr).add(str);}else{List<String> temp = new ArrayList<>();temp.add(str);map.put(orderStr,temp);}}return new ArrayList<List<String>>(map.values());}
}
1.3 最长连续序列
题目描述:
-
给定一个未排序的整数数组
nums
,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。 -
请你设计并实现时间复杂度为
O(n)
的算法解决此问题。
力扣链接:
https://leetcode.cn/problems/longest-consecutive-sequence/description【中等】
解决思路:
- 将nums数组的所有元素放入HashSet,去除重复元素
- 从序列的最小值开始找,更新最大值
核心代码:
class Solution {public int longestConsecutive(int[] nums) {// 1. 将nums数组的所有元素放入HashSet, 去除重复元素HashSet<Integer> hs = new HashSet<>();for (int i : nums){hs.add(i);}int ans = 0;for (int i : hs){// 2. 只从序列的最小值开始找if (!hs.contains(i - 1)){int curAns = 1;while(hs.contains(i+1)){i++;curAns++;}ans = Math.max(ans,curAns);}}return ans; }
}