字母异位词分组
哈希表取代两个for循环
题目:
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
我的解法:
import java.util.*;
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> hashtable = new HashMap<>();
for (String s : strs) {
char[] c = s.toCharArray();
Arrays.sort(c);
String sSort = new String(c);
if (hashtable.containsKey(sSort)) {
List<String> tempList = hashtable.get(sSort);
tempList.add(s);
hashtable.put(sSort, tempList);
} else {
List<String> list = new ArrayList<>(Arrays.asList(s));
hashtable.put(sSort, list);
}
}
List<List<String>> results = new ArrayList<>(hashtable.values());
return results;
}
}
遇到的一些问题:
- 第五行 Map<String, List> hashtable = new HashMap<String, List>(); 在使用 Map 和 List 时应该明确指定泛型类型,以避免编译器警告和类型转换问题。
- hashtable.put(sSort, hashtable.get(sSort).add(s)); 这一行存在问题。List.add() 方法返回的是一个布尔值,表示添加是否成功,并不返回列表本身。因此,这会导致编译错误。您需要先获取列表,然后将元素添加到该列表中。
- 在创建新的 ArrayList 对象时,应该使用 Arrays.asList(s),而不是 new ArrayList< String >(s),以便直接添加单个字符串作为列表中的元素。
- 通过哈希表的getOrdefault()方法可以让代码更佳简洁:
// 从哈希映射中获取键对应的异位词列表,如果不存在则返回一个新的列表
List<String> list = map.getOrDefault(key, new ArrayList<String>());
// 将当前字符串添加到异位词列表中
list.add(str);
// 将异位词列表放回哈希映射中
map.put(key, list);
- 通过groupby实现更佳简洁的代码:
//来自LeetCode大佬Sweetiee
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
return new ArrayList<>(Arrays.stream(strs)
.collect(Collectors.groupingBy(str -> {
// 返回 str 排序后的结果。
// 按排序后的结果来grouping by,算子类似于 sql 里的 group by。
char[] array = str.toCharArray();
Arrays.sort(array);
return new String(array);
})).values());
}
}
最长连续序列
哈希表
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
我的解法
class Solution {
public int longestConsecutive(int[] nums) {
int lenMax = 0;
int lenCount = 1;
int len = nums.length;
if (len==0) {return 0;}
Arrays.sort(nums);
for (int i=1;i<len;i++) {
if (nums[i]==nums[i-1]+1) {
lenCount++;
} else if (nums[i]==nums[i-1]) {
continue;
} else {
lenMax = Math.max(lenMax,lenCount);
lenCount = 1;
}
}
return Math.max(lenMax,lenCount);
}
}
不满足时间复杂度为O(n)的要求
通过哈希表:
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> num_set = new HashSet<Integer>();
for (int num : nums) {
num_set.add(num);
}
int longestStreak = 0;
for (int num : num_set) {
if (!num_set.contains(num - 1)) {
int currentNum = num;
int currentStreak = 1;
while (num_set.contains(currentNum + 1)) {
currentNum += 1;
currentStreak += 1;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
}
return longestStreak;
}
}
tips
- 通过集合实现去重
移动零
双指针
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
我的方法
class Solution {
public void moveZeroes(int[] nums) {
int n = nums.length;
int j = 0;
for (int i = 0; i < n; i++) {
if (nums[i] != 0) {
nums[j++] = nums[i];
}
}
while (j < n) {
nums[j++] = 0;
}
}
}
简单题
参考链接
https://leetcode.cn/problems/group-anagrams/
https://leetcode.cn/problems/move-zeroes/
https://leetcode.cn/problems/longest-consecutive-sequence/
文章介绍了如何用Java解决三个编程问题:字母异位词分组(使用哈希表和排序),查找最长连续序列(时间复杂度优化),以及移动数组中的零(原地操作)。作者提供了两种解决方案,并强调了代码优化和数据结构的应用。

1210

被折叠的 条评论
为什么被折叠?



