考虑用哈希表来解决问题
1.哈希表的 key : 存放排序后的字符串
2.哈希表的 value :存放与排序后字符串含有相同字母的字符串序列
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for(String str : strs){
char[] ch = str.toCharArray();
Arrays.sort(ch);
String key = new String(ch);
List<String> value = map.getOrDefault(key, new ArrayList<String>());
value.add(str);
map.put(key, value);
}
return new ArrayList<List<String>>(map.values());
}
}
考虑用哈希表来解决此问题
1. 遍历数组,将其加入 HashSet 中, 去重;
2. 遍历 HashSet , 如果存在比当前数字小一的数字,则继续(我们的目标是找到连续序列中的最小值);
3. 如果不存在比当前数字小一的数字,那么表明我们找到了连续序列中的最小值,此时在 HashSet 中寻找是否存在比该数字大一的数字,存在则最长序列的长度加一,反之则继续
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for(int num : nums) set.add(num);
int count = 0;
for(int arr : set){
if(!set.contains(arr - 1)){
int currentNumber = arr;
int currentCount = 1;
while(set.contains(currentNumber + 1)){
currentNumber += 1;
currentCount += 1;
}
count = Math.max(count, currentCount);
}
}
return count;
}
}