[刷题记录Day6]Leetcode哈希表

发布时间 2023-08-25 22:28:34作者: 喜欢毛绒绒的番茄子

No.1

题目

有效的字母异位词

思路

  • 每个字符频率都相同,于是把字母表映射到长度为26的数组上

代码

public boolean isAnagram(String s, String t) {  
    int lenS = s.length(), lenT = t.length();  
    if (lenT != lenS) return false;  
    int[] alphabet = new int[26]; // 26个字母 
    for (int i = 0; i < lenS; i++) {  
        char item = s.charAt(i);  
        alphabet[item - 'a'] += 1;  
    }  
    for (int i = 0; i < lenT; i++) {  
        char item = t.charAt(i);  
        alphabet[item - 'a'] -= 1;  
    }  
    for (int i = 0; i < 26; i++) {  
        if (alphabet[i] != 0) return false;  
    }  
    return true;  
}

No.2

题目

两个数组的交集

思路

代码

public int[] intersection(int[] nums1, int[] nums2) {  
    if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {  
        return new int[0];  
    }  
    Set<Integer> set = new HashSet<>();  
    Set<Integer> resSet = new HashSet<>();  
    // iterate nums1  
    for (int i : nums1) {  
        set.add(i);  
    }  
    // iterate nums2 & check if exists  
    for (int i : nums2) {  
        if (set.contains(i))  
            resSet.add(i);  
    }  
    // turn into int[]  
    return resSet.stream().mapToInt(x -> x).toArray();  
}

No.3

题目

快乐数

思路

  • 用一个set来记录出现过的数字,一旦重复就说明不是快乐数
  • 用一个方法获取各位数字和

代码

public boolean isHappy(int n) {  
    Set<Integer> sumHash = new HashSet<>();  
  
    while (n != 1) {  
        n = getSumForEachDigit(n);  
        if (sumHash.contains(n))  
            return false;  
        else            sumHash.add(n);  
    }  
  
    return true;  
}  
  
public static int getSumForEachDigit(int n) {  
    int sum = 0;  
    while (n >= 10) {  
        sum += (n % 10) * (n % 10);  
        n /= 10;  
    }  
    sum += n * n;  
    return sum;  
}

No.4

题目

两数之和

思路

  • map记录访问过的数,以数为key,下标为value,每访问一个新的数,就在map中寻找target-当前数这个key是否存在

代码

public int[] twoSum(int[] nums, int target) {  
    Map<Integer, Integer> hashMap = new HashMap<>();  
    int[] result = new int[2];  
    for (int i = 0; i < nums.length; i++) {  
        int match = target - nums[i];  
        // 找到匹配  
        if (hashMap.containsKey(match)) {  
            result[0] = i;  
            result[1] = hashMap.get(match);  
            return result;  
        } else { // 找不到,记录key value  
            hashMap.put(nums[i], i);  
        }  
    }  
    return result;  
}