242.有效的字母异位词
思路讲解:代码随想录:有效的字母异位词
难度:简单
-
数组其实就是一个简单哈希表,而且这道题目中字符串只有小写字符,那么就可以定义一个数组,来记录字符串s里字符出现的次数。
-
定义一个数组叫做record用来上记录字符串s里字符出现的次数。
-
需要把字符映射到数组也就是哈希表的索引下标上,因为字符a到字符z的ASCII是26个连续的数值,所以字符a映射为下标0,相应的字符z映射为下标25。(在遍历字符串s的时候,只需要将 s[i] - ‘a’ 所在的元素做+1 操作即可,并不需要记住字符a的ASCII,只要求出一个相对数值就可以了。 这样就将字符串s中字符出现的次数,统计出来了。)
-
如何检查字符串t中是否出现了这些字符:同样在遍历字符串t的时候,对t中出现的字符映射哈希表索引上的数值再做-1的操作。
-
最后检查一下,record数组如果有的元素不为零0,说明字符串s和t一定是谁多了字符或者谁少了字符,return false。
-
最后如果record数组所有元素都为零0,说明字符串s和t是字母异位词,return true。
时间复杂度为O(n),空间上因为定义是的一个常量大小的辅助数组,所以空间复杂度为O(1)。
class Solution {
public 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 i=0; i<t.length(); i++){
hash[t.charAt(i)-'a']--;
}
for(int i=0; i<26; i++){
if(hash[i] != 0){
return false;
}
}
return true;
}
}
349. 两个数组的交集
思路讲解:代码随想录: 两个数组的交集
难度:简单
特别说明:输出结果中的每个元素一定是唯一的,也就是说输出的结果的去重的, 同时可以不考虑输出结果的顺序,用hashset
方法一:用hashset
import java.util.HashSet;
import java.util.Set;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1==null||nums1.length==0||nums2==null||nums2.length==0){
return new int[0];
}
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for(int i : nums1){
set1.add(i);
}
for(int i: nums2) {
if(set1.contains(i)){
set2.add(i);
}
}
int[] result = new int[set2.size()];
int j = 0;
for(int i : set2){
result[j++] = i;
}
return result;
}
}
方法二:用hash数组
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
int[] hash1 = new int[1002];
int[] hash2 = new int[1002];
for(int i : nums1){
hash1[i]++;
}
for(int i : nums2){
hash2[i]++;
}
List<Integer> reslist = new ArrayList<>();
for(int i=0; i<1002; i++){
if(hash1[i]!=0 && hash2[i]!=0){
reslist.add(i);
}
}
int[] result = new int[reslist.size()];
int j = 0;
for(int i : reslist){
result[j++] = i;
}
return result;
}
}
202. 快乐数
思路讲解:代码随想录:快乐数
难度:简单
- 题目中说了会无限循环,那么也就是说求和的过程中,sum会重复出现
当遇到要快速判断一个元素是否出现集合里的时候,就要考虑哈希法。
- 使用哈希法来判断这个sum是否重复出现,如果重复了就是return false, 否则一直找到sum为1为止。
判断sum是否重复出现就可以使用unordered_set。
class Solution {
public boolean isHappy(int n) {
Set<Integer> record = new HashSet<>();
while(n != 1 && !record.contains(n)){
record.add(n);
n = getnumber(n);
}
return n==1;
}
public int getnumber(int n){
int res = 0;
while(n > 0){
int temp = n % 10;
res += temp * temp;
n = n/10;
}
return res;
}
}
1. 两数之和
思路讲解:代码随想录:两数之和
难度:简单
题中不仅要知道元素有没有遍历过,还要知道这个元素对应的下标,需要使用 key value结构来存放,key来存元素,value来存下标,那么使用map正合适。
使用数组和set来做哈希法的局限:
- 数组的大小是受限制的,而且如果元素很少,而哈希值太大会造成内存空间的浪费。
- set是一个集合,里面放的元素只能是一个key,而两数之和这道题目,不仅要判断y是否存在而且还要记录y的下标位置,因为要返回x 和
y的下标。所以set 也不能用。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
if(nums == null || nums.length == 0){
return res;
}
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int temp = target - nums[i];
if(map.containsKey(temp)){
res[1] = i;
res[0] = map.get(temp);
break;
}
map.put(nums[i], i);
}
return res;
}
}