242.有效的字母异位词
思路:
因为需要检查存在的元素较少,故采用数组来记录。先遍历一个字符串,对应字母的位置+1,在遍历第二个字符串,对应字母位置-1。最后检查数组是否所有的元素均为0。
代码:
class Solution {
public boolean isAnagram(String s, String t) {
//用数组实现哈希查询
int[] check = new int[26];
for(int i = 0; i < s.length(); i++){//length后不要忘记(),数组长度不需要括号
check[s.charAt(i) - 'a']++;
}
for(int i = 0; i < t.length(); i++){
check[t.charAt(i) - 'a']--;
}
for(int i = 0; i < check.length; i++){
if(check[i] != 0){
return false;
}
}
return true;
}
}
需要注意的点:
1、不需要知道每个字母的ASCII码,仅需计算每个字母和‘a’的差值并记录在数组中。
2、字符串的长度:s.length()。
349. 两个数组的交集
思路:
所包含数字少时可用数组实现,多就用set。
遍历第一个数组,将其加入set。遍历第二个数组,如果该数组中的元素在set中出现就加入res,最后将res(set型)转化为数组。
代码:
import java.util.HashSet;
import java.util.Set;
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]);
}
}
return res.stream().mapToInt(x -> x).toArray();
}
}
需要注意的点:
1、set在加入元素时会自动去重。
2、要知道set如何转化为数组。
202. 快乐数
思路:
当n各位上的平方和不为1且没有在set中出现将其加入set并更新n。在满足上述条件任意一个时终止更新,检查此时n的数值来判断是否为快乐数。
代码:
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
//循环终止条件:n=1时或set中存在n
while(n != 1 && !set.contains(n)){
set.add(n);
//更新n
n = getNextnumber(n);
}
//检查是否为快乐数
return n == 1;
}
//计算各个位置平方和后的下一个数
public int getNextnumber(int n){
int res = 0;
while(n != 0){
//获得最后一位的数
int temp = n % 10;
res += temp*temp;
n = n / 10;//去除最后一位数
}
return res;
}
}
需要注意的点:
1、如何获取和去掉n最后一位数(%10、/10)。
2、终止条件的判断。
1. 两数之和
思路:
遍历数组,如果map中出现了和目前遍历元素加和为target的数,就返回set中记录的下标和当前遍历元素的下标;否则将该元素的值和下标记录在map中。
代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
//新建存放下标的数组
int[] res = new int[2];
//<数,下标>
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
//temp为除了目前正在遍历的数,离目标还差多少
int temp = target - nums[i];
if(map.containsKey(temp)){
//目前数的下标
res[1] = i;
//temp的下标
res[0] = map.get(temp);
break;
}
map.put(nums[i], i);
}
return res;
}
}
需要注意的点:
1、数组的元素和下标都需要查询,所以用map来存储值(key)和下标(value)。
2、map查询按照键来:map.containsKey(key)
3、map返回键对应的值:map.get(key)