2 有效的字母异位词
Leetcode242 用int[26]当map
Leetcode49
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String,List<String>> map = new HashMap<>();
for(String str:strs){
int[] counts = new int[26];
int length = str.length();
for(int i=0;i<length;i++){
counts[str.charAt(i)-'a']++;
}
StringBuffer sb = new StringBuffer();
for(int i=0;i<26;i++){
if(counts[i]!=0){
sb.append((char)('a'+i));
sb.append(counts[i]);
}
}
String key = sb.toString();
List<String> list = map.getOrDefault(key,new ArrayList<String>());
list.add(str);
map.put(key,list);
}
return new ArrayList<List<String>>(map.values());
}
}
Leetcode438
class Solution {
public List<Integer> findAnagrams(String s, String p) {
int sLen = s.length();
int pLen = p.length();
if(sLen<pLen)return new ArrayList<Integer>();
List<Integer> ans = new ArrayList<>();
int[] sCount = new int[26];
int[] pCount = new int[26];
for(int i=0;i<pLen;i++){
sCount[s.charAt(i)-'a']++;
pCount[p.charAt(i)-'a']++;
}
if(Arrays.equals(sCount,pCount)){
ans.add(0);
}
for(int i=0;i<sLen-pLen;i++){
sCount[s.charAt(i)-'a']--;
sCount[s.charAt(i+pLen)-'a']++;
if(Arrays.equals(sCount,pCount)){
ans.add(i+1);
}
}
return ans;
}
}
3 两个数组的交集
Leetcode349 用set
Leetcode350
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer,Integer> map = new HashMap<>();
// Map<Integer,Integer> res = new HashMap<>();
int m = nums1.length;
int n = nums2.length;
int[] res = new int[m];
for(int i=0;i<m;i++){
map.put(nums1[i],map.getOrDefault(nums1[i],0)+1);
}
int idx = 0;
for(int i=0;i<n;i++){
if(map.containsKey(nums2[i])){
map.put(nums2[i],map.get(nums2[i])-1);
res[idx++]=nums2[i];
if(map.get(nums2[i])==0){
map.remove(nums2[i]);
}
}
}
return Arrays.copyOfRange(res,0,idx);
}
}
4 快乐数
Leetcode202 用set存每个n
5 两数之和
Leetcode1 map存nums[i]和i
6 四数相加
Leetcode454 两两组合->类似两数之和
7 赎金信
Leetcode383 用int[26]当map
8 三数之和
Leetcode15 遍历一个i,剩下两个用双指针
9 四数之和
Leetcode18 比三数之和多一层for