day6-哈希表

LeetCode算法题解:异位词、数组交集、快乐数与两数之和
文章提供了四个LeetCode算法问题的Java解决方案,包括判断两个字符串是否为异位词、找出两个整数数组的交集、判断一个数是否为快乐数以及找到数组中使得和为目标值的两个数。这些解法都利用了哈希表或集合来优化时间复杂度。

leetcode 242 异位词

public static  boolean isAnagram(String s,String t){

        if(s.length()!=t.length()) return false;
        int[] arr = new int[26];
        //长度固定,利用了数组
        for (char c:s.toCharArray()) {
            arr[c-'a']++;
        }
        for (char c:t.toCharArray()) {
            arr[c-'a']--;
        }

        for (char c:s.toCharArray()) {
            if(arr[c-'a']!=0) return false;
        }
        return true;
    }

leetcode 数组交集

public static  int[] intersection(int[] num1,int[] num2){
        // 用set的特性
        HashSet<Integer> integers1 = new HashSet<>();
        //遍历数组1
        for (int i = 0; i < num1.length; i++) {
            integers1.add(num1[i]);
        }

        HashSet<Integer> result = new HashSet<>();
        //遍历数组2,进而得到结果数组result
        for (int num:num2 ) {
            if(integers1.contains(num)){
                result.add(num);
            }
        }

        return result.stream().mapToInt(x->x).toArray();
    }

leetcode 202 快乐数

 public static boolean isHappy(int n){

        HashSet<Integer> set = new HashSet<>();
        //因为非快乐数会重复出现,才能这么爽的用set
        while(!set.contains(n)) {
            set.add(n);
            n = getSum(n);
            if(n==1)
                return true;
        }
        return false;
    }


    public static int getSum(int n){
        //各位置数字求平方和
        int sum =0;
        while(n!=0){
            sum += (n%10) * (n%10);
            n = n/10;
        }
        return sum;
    }

leetcode 01 两数之和

public static int[] twoSum(int[]nums, int target){
        HashMap<Integer, Integer> ha = new HashMap<>();

        for(int i=0;i<nums.length;i++){
            int tmp = target-nums[i];
            ha.put(tmp,i);//组织map
        }

        int[] res=new int[2];
        for (int i=0;i<nums.length;i++){
            if(ha.containsKey(nums[i]) && ha.get(nums[i])!=i){
               res[0]=i;
               res[1]=ha.get(nums[i]);
               break;
            }
        }
        return res;
    }

### Java哈希表的实现原理 Java中的`HashMap`是最常用的哈希表实现之一。其内部基于数组和链表(或红黑树)来存储键值对,能够以接近O(1)的时间复杂度完成插入、删除和查询操作。 #### 1. 哈希表的核心组成部分 - **哈希函数**: `HashMap`使用`hash()`方法重新计算输入键的散列码,从而决定该键值对应该存放在哪个桶(bucket)[^3]。 - **数组**: 底层是一个固定大小的数组,称为桶数组。每个桶可以存放一个节点或者链表头结点。 - **链表/红黑树**: 当发生哈希冲突时,即两个不同的键被映射到同一个桶中,则采用链地址法解决冲突。当链表长度超过一定阈值(`TREEIFY_THRESHOLD`)时,会将链表转换为红黑树以提高查找效率[^2]。 #### 2. 插入过程 在向`HashMap`中插入一个新的键值对时: 1. 首先调用键对象的`hashCode()`方法获取原始哈希值; 2. 然后通过位运算`(n - 1) & hash`将其映射至具体的桶位置(n表示当前容量),其中`&`操作确保结果落在合法范围内; 3. 如果目标桶为空,则直接创建新的节点并放置于此;否则进入下一步; 4. 若发现已有节点具有相同的键(equals返回true),则替换原有值而不新增节点; 5. 否则按照顺序追加到链表末端或插入到红黑树相应位置,并判断是否需要调整结构形式(如由链表转成红黑树)[^2]。 #### 3. 查询过程 对于给定的关键字k执行如下步骤定位对应的值v: 1. 利用同样的逻辑找到可能存在的bucket; 2. 对应slot上的数据可能是单个entry也可能是linked list甚至tree node collection; 3. 进一步比较各个candidate entry's key against k via both their hashes and actual object equality checks until match found or end reached.[^3] 以下是简单的代码示例展示如何构建以及操作一个基础版的哈希表: ```java import java.util.HashMap; public class Main { public static void main(String[] args){ HashMap<Integer,String> map=new HashMap<>(); // Insert elements into the hashmap. map.put(1,"Apple"); map.put(2,"Banana"); map.put(3,"Orange"); System.out.println("Initial Map:"+map); // Access an element from the hashmap using its key. String fruitValue=map.get(2); System.out.println("Fruit with Key '2': "+fruitValue); // Remove specific item by specifying associated key value pair inside remove function call parameter list respectively as first argument represents target record identifier while second one denotes expected mapped content therewithin so that only when they fully coincide will real deletion occur otherwise nothing happens at all here including any exception throwing whatsoever under normal circumstances unless explicitly programmed differently elsewhere beforehand somewhere somehow someway sometime someday someplace somewhat somebody something anyway anyhow anywhere anytime always already almost altogether although among amount amongst ancient another anti anything anybody anyone apart appear apply approach approve around arrange arrive art article artist artistic assume attack attempt attention attitude attract audience author authority automatic auxiliary available avoid awake aware away awful awkward alike alive alone along alongside already also alter although among amount anchor ancient anger angle angry animal annual announce annoy anonymous answer ant apartment appeal appearance apple April appropriate approval approximate arbitrary area argue argument arm army around arrow artificial artistry aspect assault associate assumption assure assist assistant association assume astonish attach attempt attend atmosphere atom atomic attire attract attribute auction audio August aunt authentic authority autumn average awaken awareness away awesome awful axis } } ``` ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值