代码随想录算法训练营第6天
今日任务
● 哈希表理论基础 ● 242.有效的字母异位词 ● 349. 两个数组的交集 ● 202. 快乐数 ● 1. 两数之和
链接:https://docs.qq.com/doc/DUEtFSGdreWRuR2p4 (opens in a new tab)
哈希表理论基础
242.有效的字母异位词
题解想法
定义一个大小为26的数组作为哈希表,来记录字符串里字符(小写字母)出现的次数。
class Solution {
public boolean isAnagram(String s, String t) {
int[] hash_word = new int[26];
for (int i = 0; i < s.length(); i++) {
hash_word[s.charAt(i) - 'a'] += 1;
}
for (int i = 0; i < t.length(); i++) {
hash_word[t.charAt(i) - 'a'] -= 1;
}
for (int i = 0; i < hash_word.length; i++) {
if (hash_word[i] != 0) {
return false;
}
}
return true;
}
}回顾
String的一些操作:s.charAt(i)、s.length()。
349. 两个数组的交集
自己想法
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
for (int i = 0; i < nums1.length; i++) {
set1.add(nums1[i]);
}
for (int i = 0; i < nums2.length; i++) {
if (set1.contains(nums2[i])) {
set2.add(nums2[i]);
}
}
int[] ans = new int[set2.size()];
int i = 0;
for (int elem : set2) {
ans[i] = elem;
i++;
}
return ans;
}
}回顾
Set的一些操作:add()、contains()、size()、for (int elem : set2)。
202. 快乐数
自己想法
class Solution {
public boolean isHappy(int n) {
Set<Integer> tmp_resu = new HashSet<Integer>();
int now_sum = squareSum(n);
while (now_sum != 1) {
if (tmp_resu.contains(now_sum) == false) {
tmp_resu.add(now_sum);
}
else {
return false;
}
now_sum = squareSum(now_sum);
}
return true;
}
public int squareSum(int n) {
int sum = 0;
while (n > 0) { // 计算平方和
sum += (n % 10) * (n % 10);
n = n / 10;
}
System.out.println(sum);
return sum;
}
}1. 两数之和
自己想法
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> scaned_nums = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
int need = target - nums[i];
if (scaned_nums.containsKey(need)) {
return new int[]{i, scaned_nums.get(need)};
}
else {
scaned_nums.put(nums[i], i);
}
}
// 根据题目描述,一定有解;
// 但对于程序来讲,必须保证每个分支都有return
// 故写一个[-1, -1],但这句是永远不可能走到的
return new int[]{-1, -1};
}
}回顾
-
Map的一些操作:containsKey()、get()、put()。 -
题解重点:● 为什么会想到用哈希表 ● 哈希表为什么用map ● map中的key和value用来存什么的