提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1,那么这个数就是快乐数。
一、力扣438. 找到字符串中所有字母异位词
class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new ArrayList<>();
if(s.length() < p.length()){
return res;
}
Map<Character,Integer> map = new HashMap<>();
for(char c : p.toCharArray()){
map.put(c,map.getOrDefault(c,0)+1);
}
int left = 0, right = 0, count = map.size();
while(right < s.length()){
if(right < p.length()){
if(map.containsKey(s.charAt(right))){
map.put(s.charAt(right),map.get(s.charAt(right))-1);
if(map.get(s.charAt(right)) == 0){
count --;
}
}
right ++;
}else{
if(map.containsKey(s.charAt(left))){
if(map.get(s.charAt(left)) == 0){
count ++;
}
map.put(s.charAt(left),map.get(s.charAt(left))+1);
}
left ++;
if(map.containsKey(s.charAt(right))){
map.put(s.charAt(right),map.get(s.charAt(right))-1);
if(map.get(s.charAt(right)) == 0){
count --;
}
}
right ++;
}
if(count == 0){
res.add(left);
}
}
return res;
}
}
二、力扣349. 两个数组的交集
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for(int a : nums1){
set1.add(a);
}
for(int a : nums2){
if(set1.contains(a)){
set2.add(a);
}
}
int[] res = new int[set2.size()];
int i = 0;
for(Integer a : set2){
res[i++] = a;
}
return res;
}
}
三、力扣350. 两个数组的交集 II
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer,Integer> map1 = new HashMap<>();
Map<Integer,Integer> map2 = new HashMap<>();
for(int a : nums1){
map1.put(a,map1.getOrDefault(a,0)+1);
}
for(int a : nums2){
if(map1.containsKey(a)){
map2.put(a,map2.getOrDefault(a,0)+1);
}
}
List<Integer> res = new ArrayList<>();
for(Integer a : map2.keySet()){
int min = map2.get(a) < map1.get(a) ? map2.get(a) : map1.get(a);
while(min > 0){
res.add(a);
min --;
}
}
return res.stream().mapToInt(Integer::intValue).toArray();
}
}
四、力扣202. 快乐数
class Solution {
public boolean isHappy(int n) {
boolean res = false;
Set<Integer> set = new HashSet<>();
while(!set.contains(n)){
set.add(n);
n = fun(n);
}
return n == 1;
}
public int fun(int n){
int count = 0;
while(n > 0){
int t = n%10;
n /= 10;
count += (t*t);
}
return count;
}
}
881

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



