变位词组
法1:
对每个字符串进行排序作为 key,从而实现相同的「变位词」对应同一个 key,使用哈希表进行统计
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> ans = new ArrayList<>();
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
char[] cs = s.toCharArray();
Arrays.sort(cs);
String key = String.valueOf(cs);
List<String> list = map.getOrDefault(key, new ArrayList<>());
list.add(s);
map.put(key, list);
}
for (String key : map.keySet()) {
ans.add(map.get(key));
}
return ans;
}
}
法2:
利用字符集大小有限作为切入点(只包含小写字母),使用一个大小为 2626 的数组进行计数,然后对计数后的数组统计值进行拼接,作为哈希表的 key,从而实现线性复杂度。
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> ans = new ArrayList<>();
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
int[] cnts = new int[26];
for (char c : s.toCharArray()) {
cnts[c - 'a']++;
}
StringBuilder sb = new StringBuilder();
for (int i : cnts) {
sb.append(i + "_");
}
String key = sb.toString();
List<String> list = map.getOrDefault(key, new ArrayList<>());
list.add(s);
map.put(key, list);
}
for (String key : map.keySet()) {
ans.add(map.get(key));
}
return ans;
}
}
二叉树的垂序遍历
法1:
<哈希表+DFS+排序>
class Solution {
Map<TreeNode, int[]> map = new HashMap<>();
public List<List<Integer>> verticalTraversal(TreeNode root) {
map.put(root, new int[]{0, 0, root.val});
dfs(root);
List<int[]> list = new ArrayList<>(map.values());
Collections.sort(list, (a, b) -> {
if (a[1] != b[1]) return a[1] - b[1];
if (a[0] != b[0]) return a[0] - b[0];
return a[2] - b[2];
});
int n = list.size();
List<List<Integer>> ans = new ArrayList<>();
for (int i = 0; i < n; ) {
int j = i;
List<Integer> tmp = new ArrayList<>();
while (j < n && list.get(j)[1] == list.get(i)[1]) {
tmp.add(list.get(j)[2]);
j++;
}
ans.add(tmp);
i = j;
}
return ans;
}
void dfs(TreeNode root) {
if (root == null) return;
int[] info = map.get(root);
int row = info[0];
int col = info[1];
int val = info[2];
if (root.left != null) {
map.put(root.left, new int[]{row + 1, col - 1, root.left.val});
dfs(root.left);
}
if (root.right != null) {
map.put(root.right, new int[]{row + 1, col + 1, root.right.val});
dfs(root.right);
}
}
}