一、242. 有效的字母异位词
题目链接:242. 有效的字母异位词
思路:
- 用数组做哈希映射,数组下标用字母ASCII码顺序,数组的值为字母出现的次数;
- 遍历s字符串,将对应的数组值填充为字母出现的次数;
- 遍历t字符串,每次遍历,把对应的数组值-1;
- 遍历数组,如果出现非零值,则说明不成立,反之则成立。
class Solution {
public boolean isAnagram(String s, String t) {
int[] hash = new int[26];
int sizeOfS = s.length();
int sizeOfT = t.length();
for(int i = 0; i < sizeOfS; i++){
hash[s.charAt(i) - 'a']++;
}
for(int i = 0; i < sizeOfT; i++){
hash[t.charAt(i) - 'a']--;
}
for (int i = 0; i < hash.length; i++) {
if(hash[i]!=0)
return false;
}
return true;
}
}
二、349. 两个数组的交集
题目链接:349. 两个数组的交集
思路:使用set集合做哈希映射
- 遍历nums1数组,将数组元素存入set集合中;
- 遍历nums2数组,如果nums2中的元素在set中出现过,将这个元素再存入一个新的集合(res)中(这里不知道结果res的长度,如直接存在数组中,会有多余的零导致不能通过,所以存在集合中);
- 将res集合转换为数组。
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Set<Integer> res = new HashSet<>();
for(int i = 0; i < nums1.length; i++){
set.add(nums1[i]);
}
for(int i = 0; i < nums2.length; i++){
if(set.contains(nums2[i])){
res.add(nums2[i]);
}
}
//用流的方式转为数组
int[] reslut = res.stream().mapToInt(x -> x).toArray();
return reslut;
}
}
三、202. 快乐数
题目链接:202. 快乐数
思路:
将每次的平方和存在集合中,如果之后得到的平方和在集合中能够找到,说明出现了重复,证明不是快乐数。
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
int res = n;
//如果平方和为1,退出循环
//如果集合中有这个平方和,证明有重复,不是快乐数,退出循环
while(res != 1 && !set.contains(res)){
//存入集合
set.add(res);
res = getNextNumber(res);
}
//退出循环后,如果结果是1是快乐数,反之则不是
return res == 1;
}
public int getNextNumber(int n){
int sum = 0;
int temp = 0;
while(n > 0){
//取余计算平方和
temp = n % 10;
sum += temp * temp;
//整除10,除去个位数
n = n / 10;
}
return sum;
}
}
四、1. 两数之和
题目链接:1. 两数之和
思路:
- 用map做哈希映射,key为数组值,value为数组下标;
- 遍历数组,将键值对(nums[i] , i)存入map,每次存的时候查询map中的key是否存在target - nums[i],如果有则返回数组下标,反之则没有。
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> hm = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if(hm.containsKey(target - nums[i])){
return new int[]{hm.get(target - nums[i]),i};
}
hm.put(nums[i],i);
}
return new int[0];
}
}