242. 有效的字母异位词
题目链接: 242. 有效的字母异位词 - 力扣(LeetCode)
解题思路:
int num1 = 'a'; num1的值为97
int num2 = 'b' - 'a'; num2的值为1
int num2 = 'c' - 'a'; num2的值为2
创建一个长度为26 (小写字母的个数) 的数组.
小写字母,相比字母的顺序, 对应在阿斯克码表中的值是连续递增的.
单独的字符相减得到的数字,把他们映射到数组的索引位置上,根据映射到的次数,做增加操作.这样就有了字符串s的各个字母出现的位置 和 出现次数的对应关系了.
再去遍历字符串t,映射到对应的次数,做减少次数的操作.
最后遍历数组,如果存在元素的值不为空,说明 字符串s 和t中存在字母出现的次数不一样,返回false; 否则true.
参考答案:
class Solution {
public boolean isAnagram(String s, String t) {
char[] chars1 = s.toCharArray();
int[] arr = new int[26];
for (int i = 0; i < chars1.length; i++) {
arr[chars1 [i]-'a']++;
}
char[] chars2 = t.toCharArray();
for (int i = 0; i < chars2.length; i++) {
arr[chars2[i]-'a']--;
}
for (int i = 0; i < arr.length; i++) {
if( arr[i]!=0){
return false;
}
}
return true;
}
}
349. 两个数组的交集
题目链接: https://leetcode.cn/problems/intersection-of-two-arrays/
解题思路:
java中的hashset 可以去重. 答案要求: 输出的结果,每个元素唯一,这就需要去重.
先遍历数组 nums1 ,把遍历的元素 存到hashset中,每个元素都是唯一的,已经去重了.
再遍历 nums2 , 判断遍历时的元素在 hashset 是否存在,如果存在,存入到新的集合 hashset中.
最后,把新集合 hashset 转变成数组 返回.
参考答案:
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> hashSet = new HashSet<>();
for (int num1: nums1) {
hashSet.add(num1);
}
HashSet<Integer> hashSet2 = new HashSet<>();
for (int num2 : nums2) {
if(hashSet.contains(num2)) {
hashSet2.add(num2);
}
}
int[] array = hashSet2.stream().mapToInt(s -> s).toArray();
return array;
}
}
● 202. 快乐数
题目链接: https://leetcode.cn/problems/happy-number/
解题思路:
先提取一个需要重复执行的方法,方法内容: 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,返回最后的和.
对整数n %10,获取个位数temp, 累加temp的平方 到 num 上.
在对n/10 获取 temp之前的数字,重新赋值给n. 只要n>0,就可以一直while 循环.
将返回的值,如果不存在,添加到arrayList中, 如果存在,就遇到重复值了, 就判断n==1,
返回Boolean了.
同时,在while 循环条件上 判断 返回的值是否是1,是1,原来的整数n,就是快乐数,满足条件,返回true.
否则,继续while循环,直到 遇到重复值,再做判断.
参考答案:
class Solution {
public boolean isHappy(int n) {
HashSet<Integer> hashSet = new HashSet<>();
while (n != 1 ) {
if( ! hashSet.contains(n)){
hashSet.add(n);
n = get(n);
} else {
return n==1;
}
}
return n==1;
}
public int get(int n) {
int num = 0;
while (n > 0) {
// 一个变量temp 记录每次去做平方乘法的末尾的数
// 一个变量n记录每次去除去 末尾的数 剩余的数
// 第二个变量是不断被被循环的遍历 就用n 累加和用num
int temp = n % 10;
num += temp * temp;
n = n / 10;
}
return num;
}
}
1. 两数之和
解题思路:
遍历数组, 把元素和元素对应 的索引存在hashmap 的 键和值当中.
同时,判断target 减去当前元素的差值是否在hashmap中出现,存在的话,获取当前元素和对应差值的索引,保存到数组中 ,返回.
参考答案:
class Solution {
public static int[] twoSum(int[] nums, int target) {
int[] arr = new int[2];
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if(hashMap.containsKey(target-nums[i])){
int num1 = hashMap.get(target - nums[i]);
arr[0]= num1;
arr[1]= i;
}
hashMap.put( nums[i],i);
}
return arr;
}
}