242.有效的字母异位词
此题根据题意便是判断字符串中是否出现了相同次数的相同字母,所以便创建数组记录字母出现的次数
代码如下:
class Solution {
public boolean isAnagram(String s, String t) {
int[] count1 = new int[26];
int[] count2 = new int[26];
for(char ss : s.toCharArray()){
int n1 = ss - 'a';
count1[n1]++;
}
for(char tt : t.toCharArray()){
int n2 = tt - 'a';
count2[n2]++;
}
for(int i = 0;i<26;i++){
if(count1[i] != count2[i]){
return false;
}
}
return true;
}
}
349. 两个数组的交集
读题分析题意,要求找数组交集则是找寻一个数组中的元素并且在另一个数组中也存在的元素,要求输出结果唯一,则可得到:
找寻一个数组中的元素并且在另一个数组中也存在的元素 >>> 利用哈希表,则可以快速判断一个元素是否存在于集合里
代码如下:
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set = new HashSet<>();
List<Integer> res = new ArrayList<>();
for(int i = 0;i < nums1.length;i++){
set.add(nums1[i]);
}
for(int j = 0;j < nums2.length;j++){
if(set.contains(nums2[j])){
res.add(nums2[j]);
set.remove(nums2[j]); // 去重操作
}
}
int[] result = new int[res.size()];
for(int p = 0;p<res.size();p++){
result[p] = res.get(p);
}
return result;
}
}
202. 快乐数
该题其实也就是找规律看是否有重复出现的值,则还是使用HashSet
代码如下:
class Solution {
public boolean isHappy(int n) {
HashSet<Integer> set = new HashSet<>();
while(n != 1){
int sum = 0;
while(n != 0){
int t = n % 10;
n = n / 10;
sum += t * t;
}
if(set.contains(sum)){
return false;
}else{
set.add(sum);
n = sum;
}
}
return true;
}
}
1. 两数之和
根据卡哥的讲解直接上图(此题为什么选择使用HashMap!!!)
清楚为什么使用HashMap后,便想明白四点:
- 为什么会想到用哈希表
- 哈希表为什么用map
- 本题map是用来存什么的
- map中的key和value用来存什么的
再给出代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<>();
int[] res = new int[2];
for(int i = 0;i < nums.length;i++){
int need = target - nums[i];
if(map.containsKey(need)){
res[0] = map.get(need);
res[1] = i;
return res;
}
map.put(nums[i],i); // 如果没有在map中找到另一个值,则把访问过的元素加入map中
}
return res;
}
}