哈希表
哈希表是根据关键码的值而直接进行访问的数据结构
哈希表是常用于快速判断一个元素是否出现集合里
哈希结构
- 数组
- set(集合)
- map(映射)
6-1.242题有效的字母异位词
题目
思路
数组也是哈希表
代码
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;
}
}
总结
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
1
)
O(1)
O(1)
6-2.349题两个数组的交集
题目
思路
考虑哈希数据结构unordered_set
代码
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> res = new HashSet<>();
for (int i : nums1) {
set1.add(i);
}
for (int i : nums2) {
if (set1.contains(i)) {
res.add(i);
}
}
int[] result = new int[res.size()];
int j = 0;
for (int i : res) {
result[j++] = i;
}
return result;
}
}
总结
时间复杂度:
O
(
m
n
)
O(mn)
O(mn)
空间复杂度:
O
(
n
)
O(n)
O(n)
6-3.202题快乐数
题目
思路
将n的每一位拆出来,然后计算平方操作,直到最终结果为1或无限循环不为1
代码
class Solution {
public boolean isHappy(int n) {
Set<Integer> record = new HashSet<>();
while (n != 1 && !record.contains(n)) {
record.add(n);
n = getNextNum(n);
}
return n == 1;
}
private int getNextNum(int n) {
int res = 0;
while (n > 0) {
int tmp = n % 10;
res += tmp * tmp;
n = n / 10;
}
return res;
}
}
总结
时间复杂度 :
O
(
l
o
g
n
)
O(log n)
O(logn)
空间复杂度 :
O
(
l
o
g
n
)
O(log n)
O(logn)
6-4.1题两数之和
题目
思路
使用map
代码
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int tmp = target - nums[i];
if (map.containsKey(tmp)) {
res[1] = i;
res[0] = map.get(tmp);
break;
}
map.put(nums[i], i); //没找到匹配就把访问过的元素和下标加入map
}
return res;
}
}
总结
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
n
)
O(n)
O(n)