当前位置: 首页 > article >正文

LeetCode——哈希表(Java)

哈希表

  • 简介
  • [简单] 242. 有效的字母异位词
  • [简单] 349. 两个数组的交集
  • [简单] 202. 快乐数
  • [简单] 1. 两数之和
  • [中等] 454. 四数相加 II
  • [简单] 383. 赎金信
  • [中等]15. 三数之和

简介

记录一下自己刷题的历程以及代码。写题过程中参考了 代码随想录。会附上一些个人的思路,如果有错误,可以在评论区提醒一下。

什么类型的题应该是用哈希表的思想?
需要快速判断一个元素是否出现集合里时。

[简单] 242. 有效的字母异位词

原题链接

最容易想到的就是开两个 26 大小的数组分别做字符统计,然后比较,稍微简化一些可以在单个数组上做统计比对。
这道题放在哈希表系列之下,我想s.charAt(i) - 'a'就是一种hashFunction(),把每个字符对应到一个数组下标从而进行统计

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 = 0; i < 26; i++){
            if(count[i] != 0) return false;
        }
        return true;
    }
}

[简单] 349. 两个数组的交集

原题链接

方法①:使用HashSet 写起来方便,效率比较低

class Solution {
     public int[] intersection(int[] nums1, int[] nums2)  {
        HashSet<Integer> set1 = new HashSet<>();
        HashSet<Integer> set2 = new HashSet<>();
        for( int i : nums1){
            set1.add(i);
        }
        for( int i : nums2){
            if(set1.contains(i)){
                set2.add(i);
            }
        }
        return set2.stream().mapToInt(x -> x).toArray();
    }
}

方法②:List + 数组遍历

public int[] intersection(int[] nums1, int[] nums2)  {
        int[] count1 = new int[1001];
        int[] count2 = new int[1001];
        List<Integer> ansList = new ArrayList<>();
        for(int i = 0; i < nums1.length; i++){
            count1[nums1[i]]++;
        }
        for(int i = 0; i < nums2.length; i++){
            if(count1[nums2[i]] != 0 && count2[nums2[i]] == 0){
                count2[nums2[i]]++;
                ansList.add(nums2[i]);
            }
        }
        int ans[] = new int[ansList.size()];
        int index = 0;
        for(int i : ansList){
            ans[index++] = i;
        }
        return ans;
    }

方法①和方法②的效率差距:
在这里插入图片描述

[简单] 202. 快乐数

原题链接

题目中说不是快乐数的情况下,sum会一直循环,也就是当sum重复出现的时候,他就不会是一个快乐数了(这个我感觉题面上给的不是很直接),那么只要对sum出现的情况做统计,就可以判断n是否是快乐数。

方法①:在数组上进行统计,int类型最大值 2147483645 最大的情况下也就是十位数,每一位平方总和不会大于 9 * 9 *10;

class Solution {
    public boolean isHappy(int n) {
        int[] count = new int[850];
        while(n != 1){
            int sum = 0;
            while(n > 0){
                sum += (n % 10) * (n % 10);
                n = n / 10;
            }
            if(count[sum] != 0) return false;
            count[sum]++;
            n = sum;
        }
        return true;
    }
}

方法②:利用HashSet做统计,HashSet不会储存重复的元素。

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

[简单] 1. 两数之和

原题链接

题目已经给定了样例情况只会有一对正确答案,所以整体上不需要多少边界判断,也可以自己适当做一些细化的处理。

方法①:最简单的思路就是二重循环遍历判断,时间效率上肯定比较低,时间复杂度O(n^2)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for(int i = 0; i < nums.length - 1; i++){
            for(int j = i + 1; j < nums.length; j++){
                if(nums[i] + nums[j] == target){
                    return new int[]{i, j};
                }
            }
        }
        return new int[]{-1, -1};
    }
}

方法②:使用HashMap映射,遍历每个元素的时候去map中查找target - nums[i]是否已经在map中,有则返回,否则放入当前元素,继续遍历,时间复杂度O(n)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++){
            if(map.containsKey(target - nums[i]))
                return new int[]{map.get(target - nums[i]), i};
            map.put(nums[i], i);
        }
        return new int[]{-1, -1};
    }
}

方法①和方法②的效率差距:
在这里插入图片描述

[中等] 454. 四数相加 II

原题链接

暴力解法的话,四重循环时间复杂度是O(n^4),这显然不太合适。
跟上面一题思路类似,当考虑nums1[i] + nums2[j]中的i和j是否是一组答案中的一部分时,考虑是否有nums3[i] + nums4[j]是前者的相反数即可。所以只需要对nums1和nums2做二重循环记录所有的相加的结果,再到nums3和nums4中做二重循环,看相反数是否包含在上面的记录中。
使用HashMap时,本题不需要记录下标,所以map中的value可以设置为这一组值出现的次数,(map不记录重复的key)。

public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        HashMap<Integer ,Integer> map = new HashMap<>();
        int count = 0;
        for(int i = 0; i < nums1.length; i++){
            for(int j = 0; j < nums2.length; j++){
                if(map.containsKey(nums1[i] + nums2[j]))
                    map.put(nums1[i] + nums2[j], map.get(nums1[i] + nums2[j]) + 1);
                else map.put(nums1[i] + nums2[j], 1);
            }
        }
        for(int i = 0; i < nums3.length; i++) {
            for (int j = 0; j < nums4.length; j++) {
                if(map.containsKey(0 - nums3[i] - nums4[j]))
                    count += map.get(0 - nums3[i] - nums4[j]);
            }
        }
        return count;
    }

[简单] 383. 赎金信

原题链接
思维惯性想到HashMap,因为上面的题写多了,但其实这题简单题直接用数组统计就行了。
代码随想录:
在这里插入图片描述

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] count = new int[26];
        for(int i = 0; i < magazine.length(); i++){
            count[magazine.charAt(i) - 'a']++;
        }
        for(int i = 0; i < ransomNote.length(); i++){
            if(count[ransomNote.charAt(i) - 'a'] == 0){
                return false;
            }
            count[ransomNote.charAt(i) - 'a']--;
        }
        return true;
    }
}

[中等]15. 三数之和

原题链接


http://www.kler.cn/news/108981.html

相关文章:

  • uni-app中tab选项卡的实现效果 @click=“clickTab(‘sell‘)“事件可传参数
  • No175.精选前端面试题,享受每天的挑战和学习
  • 【算法与数据结构】--算法应用--算法和数据结构的案例研究
  • ubuntu部署个人网盘nextCloud使用docker-compose方式
  • 性能优化必读 | AntDB-M高性能设计之线程池协程模型
  • Docker底层原理:Cgroup V2的使用
  • centos7 部署 Flink
  • 设计模式——单例模式详解
  • 随笔:使用Python爬取知乎上相关问题的所有回答
  • 【CSS】伪类和伪元素
  • C#WPFPrism框架导航应用实例
  • sprinbboot 2.7启动不生成日志文件
  • 电子电器架构 —— 车载网关初入门(二)
  • 【C++代码】爬楼梯,不同路径,整数拆分,不同搜索树,动态规划--代码随想录
  • 泰州市旅游景点门票预订管理系统 vue+uniapp微信小程序
  • C#:枚举是命名的整形常量的集合
  • 什么是 Node.js
  • ESM蛋白质语言模型系列
  • 202310-MetaPhlAn4安装和使用方法-Anaconda3- centos9 stream
  • Anaconda下载和安装
  • hdlbits系列verilog解答(8位宽移位寄存器)-24
  • LangChain+LLM实战---BERT主要的创新之处和注意力机制中的QKV
  • MyBatis-Plus 实战教程四 idea插件
  • IP地址与代理ip在网络安全中的关键作用
  • 震惊!图文并茂——Java后端如何响应不同格式的数据给前端(带源码)
  • 信息系统项目管理师教程 第四版【第5章-信息系统工程-思维导图】
  • 简单而高效:使用PHP爬虫从网易音乐获取音频的方法
  • 在Go中处理时间数据
  • C++STL----list的模拟实现
  • React Hooks还有哪些常用的用法?