提示:做哈希法相关的题目,一定要记住,当我们要快速判断一个元素是否出现集合里的时候,就要考虑哈希法。
242.有效的字母异位词
思路:哈希法。利用数组来记录出现的字母个数,然后判断是否为字母异位词。
时间复杂度:O(n)
class Solution {
public boolean isAnagram(String s, String t) {
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a']++;
}
for (int i = 0; i < t.length(); i++) {
count[t.charAt(i) - 'a']--;
}
for (int i : count) {
if (i != 0) {
return false;
}
}
return true;
}
}
349. 两个数组的交集
思路:哈希法。利用HashSet集合来判断元素是否存在,set集合判断元素是否存在的时间复杂度为O(1)。注意,这里涉及将集合转换为int数组的操作
时间复杂度:O(n)
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
// 存入set,然后遍历set
Set<Integer> set1 = new HashSet<>();
Set<Integer> result = new HashSet<>();
for (int num : nums1) {
set1.add(num);
}
for (int num : nums2) {
if (set1.contains(num)) {
result.add(num);
}
}
return result.stream().mapToInt(x -> x).toArray();
}
}
202. 快乐数
思路:哈希法加数据的基本操作,使用HashSet集合来检测是否循环。
时间复杂度:里面while循环的时间复杂度为O(logn),因为数字的位数由logn决定。
class Solution {
public boolean isHappy(int n) {
Set<Integer> contain = new HashSet<>();
int count = 0;
while (n != 1) {
while (n != 0) {
count += Math.pow(n % 10, 2);
n = n / 10;
}
if (contain.contains(count)) {
return false;
}
contain.add(count);
n = count;
count = 0;
}
return true;
}
}
1. 两数之和
思路:哈希法,使用HashMap集合key存放元素value存放下标,遍历一遍数组,判断Map集合中是否有符合条件的元素,如果有,返回两个元素的下标,每次判断结束要将当前元素值和下标存放进Map集合。注意,为了防止当前元素也是符合条件的元素(即两个当前元素相加为目标值)导致的两个下标相同,所以要在判断结束之后再将当前元素和下标放进Map集合。
时间复杂度:O(n)
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
result[0] = i;
result[1] = map.get(target - nums[i]);
}
map.put(nums[i], i);
}
return result;
}
}