文章目录
一、LeetCode 242.有效的字母异位词
链接:242. 有效的字母异位词 - 力扣(LeetCode)
方法:数组作哈希表
1. 思路
因为题目要求只有26个小写字母,长度是固定的,所有可以想到用数组来当哈希表,数组大小设置为26即可。回过头再来看,字母a到z在ASCII码上是连续的26个字母,所以直接定于长度为26的数组即可完成映射。
- 遍历字符串1,让
s1[i] - 'a'
的所在索引上的元素+1
,这样就可以算出每个位置上的字母出现的次数,不需要知道没有字母是什么。 - 在遍历字符串2,在
s2[i] - 'a'
的索引上的元素-1
,遍历结束后,如果两个字符串上出现的字母个数是相同的,那么数组就会全部为0。
2. 代码实现
class Solution {
public boolean isAnagram(String s, String t) {
int[] record = new int[26];
for(int i = 0; i < s.length(); i++){
record[s.charAt(i) - 'a']++;
}
for(int i = 0; i < t.length(); i++){
record[t.charAt(i) - 'a']--;
}
for(int count:record){
if(count != 0){
return false;
}
}
return true;
}
}
3. 复杂度分析
所以循环的遍历长度都为N,所以时间复杂度为 O(n)
,定义的数组长度是固定的,空间复杂度为 O(1)
。
二、LeetCode349. 两个数组的交集
链接:349. 两个数组的交集 - 力扣(LeetCode)
方法:数组做哈希表
1. 思路
leetcode 上限制了数据的范围,所以也可以使用数组来做哈希表。
- 创建一个
HashSet
用于对结果去重,创建一个长度比 1000 大一点的数组 。 - 遍历
nums1
,将数值作为数组的索引,如果出现过就赋值为1,重复出现的数组也是赋值为1,对重复的数据不受影响。 - 遍历
nums2
,将数值作为数组的索引,看对应位置上的数值是否为 0 , 如果不为零说明,这个位置上的数值出现过,加入到HashSet
集合中去。 - 遍历结束后,
HashSet
集合转为数组输出。
2. 代码实现
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> resSet = new HashSet<>();
int[] record = new int[1005];
for(int i = 0; i < nums1.length; i++){
record[nums1[i]] = 1;
}
for(int i = 0; i < nums2.length; i++){
if(record[nums2[i]] != 0){
resSet.add(nums2[i]);
}
}
return resSet.stream().mapToInt(x -> x).toArray();
}
}
3. 复杂度分析
时间复杂度:O(N)
空间复杂度:O(N)
Reference
三、LeetCode202. 快乐数
方法:HashSet做哈希表
1. 思路
- 计算出每个位置上平和相加后的数加入 HashSet中去
- 在每次进行计算前,判断当前的数是否出现在 HashSet 中,如果出现返回 false ,如果当前数为 1 则返回 true
2. 代码实现
class Solution {
public boolean isHappy(int n) {
Set<Integer> record = new HashSet<>();
while (n != 1 && !record.contains(n)){
record.add(n);
n = getNextNumber(n);
}
return n == 1;
}
// 计算每个位置的平方和
public int getNextNumber(int n){
int sum = 0;
while(n > 0){
int temp = n%10;
sum += temp*temp;
// 下个位置上的数
n = n/10;
}
return sum;
}
}
3. 复杂度分析
时间复杂度和空间复杂度均为O(N)
Reference