代码随想录算法训练营第六天|242.有效的字母异位词、349. 两个数组的交集、202. 快乐数、1. 两数之和
242.有效的字母异位词
解题思路
- 字母是连续的
- 创建一个连续的数组用来计数
- 正着加,反着减
- 最后看这个数组的元素是不是都是零
- 返回判断结果
代码
public class IsAnagram {
static boolean isAnagram(String s, String t) {
int[] hash = new int[26];
for (int i = 0; i < s.length(); i++) {
hash[s.charAt(i) - 'a']++;
}
for (int j = 0; j < t.length(); j++) {
hash[t.charAt(j) - 'a']--;
}
for (int n = 0; n < 26; n++) {
if (hash[n] != 0) {
return false;
}
}
return true;
}
}
349. 两个数组的交集
解题思路
- 使用hashSet去重
- 遍历数组二获得交集(也是去重的set)
- 最后set转数组
代码
public class Intersection {
static int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return new int[0];
}
Set<Integer> set1 = new HashSet<>();
Set<Integer> resSet = new HashSet<>();
for (int e : nums1) {
set1.add(e);
}
for (int e : nums2) {
if (set1.contains(e)) {
resSet.add(e);
}
}
return resSet.stream().mapToInt(e -> e).toArray();
// int[] arr = new int[resSet.size()];
// int j = 0;
// for(int i : resSet){
// arr[j++] = i;
// }
//
// return arr;
}
}
202. 快乐数
解题思路
- 如何获得每一个位置的数的总和(java基础 ,基数/取余)
- 获得总和,并且加到总和set
- 当总和set中遇到重复总和 或者 总和等于1的时候,循环break
- 返回总和是否==1 得到是不是快乐数
代码
public class IsHappy {
public static void main(String[] args) {
System.out.println(getSum(100));
}
static boolean isHappy(int n) {
Set<Integer> record = new HashSet<>();
while (n != 1 && !record.contains(n)) {
record.add(n);
n = getSum(n);
}
return n == 1;
}
static int getSum(int n) {
int sum = 0;
while (n > 0) {
int temp = n % 10;
sum += temp * temp;
n = n / 10;
}
return sum;
}
}
1.两数之和
代码
public class TwoSum {
static int[] twoSum(int[] nums, int target) {
// 两数集合
int[] res = new int[2];
if (nums == null || nums.length == 0) {
return res;
}
// 定义map 存放遍历过的元素
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int temp = target - nums[i]; // 遍历当前元素,并在map中寻找是否有匹配的key
if (map.containsKey(temp)) {
res[1] = i;
res[0] = map.get(temp);
break;
}
map.put(nums[i], i); // 如果没找到匹配对,就把访问过的元素和下标加入到map中
}
return res;
}
}
思考
为什么会想到用哈希表
每种输入只会对应一个答案
哈希表为什么用map
每一个差值,应该记录一个角标(而集合可以单独设置出来)
本题map是用来存什么的/map中的key和value用来存什么的
需要记录角标,最好是唯一角标
每一个差值 对应唯一一个角标
这个差值没有 则像数组里放差值为key,value为角标,遍历的i为另一个的角标