代码随想录算法训练营第六天 | 哈希表理论基础 、有效的字母异位词、两个数组的交集、快乐数、两数之和

哈希表理论基础

用于找是否存在的数,之前都是用数组模拟,还是第一次用哈希表

有效的字母异位词

用两个哈希表对比,或者开字母表

/*
 * @lc app=leetcode.cn id=242 lang=java
 *
 * [242] 有效的字母异位词
 */

// @lc code=start
class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        int[] letter = new int[26];
        for (int i = 0; i < s.length(); i++) {
            letter[s.charAt(i) - 97] += 1;
        }
        for (int i = 0; i < t.length(); i++) {
            letter[t.charAt(i) - 97] -= 1;
        }
        for (int i = 0; i < letter.length; i++) {
            if(letter[i] != 0){
                return false;
            }
        }
        return true;
    }
}
// @lc code=end

两个数组的交集

同有效的字母异位词

/*
 * @lc app=leetcode.cn id=349 lang=java
 *
 * [349] 两个数组的交集
 */

// @lc code=start

import java.util.ArrayList;
import java.util.HashSet;

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        HashSet<Integer> a = new HashSet<>();
        HashSet<Integer> b = new HashSet<>();
        for (int i = 0; i < nums1.length; i++) {
            a.add(nums1[i]);
        }
        for (int i = 0; i < nums2.length; i++) {
            if (a.contains(nums2[i])) {
                b.add(nums2[i]);
            }
        }
        int[] result = new int[b.size()];
        int i = 0;
        for (int j : b) {
            result[i++] = j;
        } 
        return result;
    }
}
// @lc code=end

快乐数

同上,增加了数取位平方的算法

/*
 * @lc app=leetcode.cn id=202 lang=java
 *
 * [202] 快乐数
 */

// @lc code=start

import java.util.HashSet;

class Solution {
    public boolean isHappy(int n) {
        HashSet<Integer> a = new HashSet<>();
        int sum = n;
        while (!a.contains(sum) && n!=1) {
            a.add(sum);
            sum = com_sum(sum);
        }
        return sum == 1;
    }

    private int com_sum(int n){
        int ones = 0;
        int sum = 0;
        while (n > 0) {
            ones = n % 10;
            n = n / 10;
            sum += ones * ones;
        }
        return sum;
    }
}
// @lc code=end

两数之和

第一次用hashmap,用来保存键值对

/*
 * @lc app=leetcode.cn id=1 lang=java
 *
 * [1] 两数之和
 */

// @lc code=start

import java.util.HashMap;
class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> a = new HashMap<>();
        int [] result = new int[2];
        for (int i = 0; i < nums.length; i++) {
            a.put(target - nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            if (a.containsKey(nums[i])) {
                if(a.get(nums[i]) != i){
                    result[0] = a.get(nums[i]);
                    result[1] = i;
                }
            }
            
        }
        return result;
    }
}
// @lc code=end
posted @ 2026-03-09 23:00  月鸣  阅读(0)  评论(0)    收藏  举报