classSolution { public List<List<String>> groupAnagrams(String[] strs) { Map<String, List<String>> m = newHashMap<>(); for (String s : strs) { char[] sortedS = s.toCharArray(); Arrays.sort(sortedS); m.computeIfAbsent(newString(sortedS), _ -> newArrayList<>()).add(s); } returnnewArrayList<>(m.values()); } }
128. 最长连续序列 Java
创建哈希集合Set<Integer> st = new HashSet<>();, 将nums中的数加入st.add(), 遍历哈希集合, 如果 x -1在哈希集合st.contains(x-1),即x不是序列起点,直接跳过, x 是序列起点,不断查找下一个数是否在哈希集合中,循环结束后, y-1 是最后一个在哈希集合的数,从 x 到 y-1 一共 y-x 个数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { publicintlongestConsecutive(int[] nums) { Set<Integer> st = newHashSet<>(); for (int num : nums) { st.add(num); } intans=0; for (int x : st){ if (st.contains(x - 1)) continue; inty= x + 1; while (st.contains(y)) y++; ans = Math.max(ans, y - x); } return ans; } }