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

算法训练营day06 哈希表(统计数,去重,降低时间复杂度)

💡 解题思路

  1. 📝 确定输入与输出
  2. 🔍 分析复杂度
  3. 🔨 复杂题目拆分严谨且完整 地拆分为更小的子问题(哈希表的使用场景)–(多总结
  4. 💭 选择处理逻辑: 根据拆分后的子问题,总结并选择合适的问题处理思路
  5. 🔎 检查特殊情况:边界条件和特殊情况
  6. 🏁 返回结果

● 242.有效的字母异位词 (做统计)

class Solution {public boolean isAnagram(String s, String t) {if (s.length() != t.length()) {return false;}int[] table = new int[26];for (int i = 0; i < s.length(); i++) {table[s.charAt(i) - 'a']++;}for (int i = 0; i < t.length(); i++) {table[t.charAt(i) - 'a']--;if (table[t.charAt(i) - 'a'] < 0) return false;}return true;}
}

● 349. 两个数组的交集 (Set 去重)

class Solution {public static int[] intersection(int[] nums1, int[] nums2){if (nums1.length == 0 || nums2.length == 0) {return new int[0];}int len1 = nums1.length, len2 = nums2.length;Set<Integer> set = new HashSet<>(); // 确保不重复for (int num : nums1) {set.add(num);}List<Integer> res = new ArrayList<>(); // 动态数组记录结果for (int num : nums2) {if (set.contains(num)) {res.add(num);set.remove(num);}}int[] result = new int[res.size()];for (int i = 0; i < res.size(); i++) {result[i] = res.get(i);}return result;}
}

● 202. 快乐数(快慢指针的实际应用(变体)

class Solution {public boolean isHappy(int n) {if (n == 1 || getNext(n) == 1) return true;int slow = n;int fast = getNext(n);while (fast != 1 && slow != fast) {slow = getNext(slow);fast = getNext(getNext(fast));}return fast == 1;}private int getNext(int n) {int totalSum = 0;while (n > 0) {int d = n % 10;n = n / 10;totalSum += d * d;}return totalSum;}
}

● 1. 两数之和 (哈希表降低时间复杂度)

class Solution {public int[] twoSum(int[] nums, int target) {if (nums.length <= 1) {return new int[2];}HashMap<Integer, Integer> map = new HashMap<>();int len = nums.length;for (int i = 0; i < len; i++) {if (!map.containsKey(nums[i])) {map.put(target-nums[i], i);} else {return new int[] {i, map.get(nums[i])};}}return new int[2];}
}
http://www.lryc.cn/news/389080.html

相关文章:

  • 影帝郭晋安关联保健品企业,草姬集团无研发费用销售成本不低
  • leetcode-19-回溯-组合问题(剪枝、去重)
  • Java案例实现双色球
  • JS(JavaScript)的BOM操作
  • 【CT】LeetCode手撕—82. 删除排序链表中的重复元素 II
  • C++ STL unique_ptr智能指针源码剖析
  • Unity中的的文件夹(特殊文件夹)
  • Go语言定时器Timer和Ticker到底怎么用
  • 41、web基础和http协议
  • 6-173 二分查找的关键字比较次数
  • 【基础篇】第5章 Elasticsearch 数据聚合与分析
  • 【网络安全】修改Host文件实现域名解析
  • Spring Boot 全面解析:从入门到实践案例
  • 222222222
  • Boost 智能指针
  • 在WSL Ubuntu中启用root用户的SSH服务
  • C语⾔数据类型和变量
  • 运行时类型信息(RTTI)
  • 使用 NVivo 定性数据分析软件指导癌症护理研究
  • R语言 | 使用ggplot绘制柱状图,在柱子中显示数值和显著性
  • 第十四届蓝桥杯省赛C++B组D题【飞机降落】题解(AC)
  • 容器化spring boot应用程序
  • 掌握智慧校园:资产来源功能解析
  • 基于公有云部署wordpress
  • vite+vue集成cesium
  • 2024 年江西省研究生数学建模竞赛A题:交通信号灯管理问题分析、实现代码及参考论文
  • 华为机试HJ1字符串最后一个单词的长度
  • 排序(冒泡排序、选择排序、插入排序、希尔排序)-->深度剖析(一)
  • (2024)docker-compose实战 (6)部署前端项目(react, vue)
  • python 中的 下划线_ 是啥意思