文章目录
leetcode刷题笔记15——哈希表
有关哈希的介绍可以参考[XJTUSE]数据结构学习——散列(哈希)
有效的字母异位数
题目
示例
代码
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length())
return false;
int[] hash = new int[26];
for (int i = 0; i < s.length(); i++) {
hash[s.charAt(i) - 'a']++;
hash[t.charAt(i) - 'a']--;
}
for (int i = 0; i < 26; i++) {
if (hash[i] != 0)
return false;
}
return true;
}
}
两个数组的交集
题目
示例
代码
public class Intersection {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> hash1 = new HashSet<>();
HashSet<Integer> hash2 = new HashSet<>();
for (int i : nums1) {
hash1.add(i);
}
for (int j : nums2) {
if (hash1.contains(j)) {
hash2.add(j);
}
}
int[] result = new int[hash2.size()];
int i = 0;
for (Integer n : hash2) {
result[i++] = n;
}
return result;
}
}
快乐数
题目
示例
代码
class Solution {
public int getNumber(int n) {
int result = 0;
while (n > 0) {
int temp = n % 10;
result += temp * temp;
n = n / 10;
}
return result;
}
public boolean isHappy(int n) {
HashSet<Integer> resultSet = new HashSet<>();
while (true) {
if (resultSet.contains(n)) {
return false;
}
if (n == 1)
return true;
resultSet.add(n);
n = getNumber(n);
}
}
}
两数之和
题目
示例
代码
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashMap = new HashMap<>();
for(int i =0;i<nums.length;i++) {
if(hashMap.containsKey(target-nums[i])) {
return new int[]{hashMap.get(target - nums[i]), i};
}
hashMap.put(nums[i], i);
}
return new int[0];
}
}
四数相加Ⅱ
题目
示例
代码
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map<Integer, Integer> map = new HashMap<>();
统计两个数组中的元素之和,同时统计出现的次数,放入map
for (int i : nums1) {
for (int j : nums2) {
int temp = i + j;
if (map.containsKey(temp)) {
map.put(temp, map.get(temp) + 1);
} else {
map.put(temp, 1);
}
}
}
//统计剩余的两个元素的和,在map中找是否存在相加为0的情况,同时记录次数
int count = 0;
for (int k : nums3) {
for (int l : nums4) {
int temp = 0 - k - l;
if (map.containsKey(temp))
count += map.get(temp);
}
}
return count;
}
}
参考资料
有效的字母异位词
两个数组的交集
快乐数
两数之和
四数相加 II