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

代码随想录算法训练营第四天| 242.有效的字母异位词 、 349. 两个数组的交集 、 202. 快乐数 、1. 两数之和

242.有效的字母异位词 

思路:设立一个数组(int(26)),每个位置存放26个英文字母的数量,然后遍历统计第一个字符串中的字母出现的数量,遍历第二个字符串时,让对应的字母位置的数字-1,最后看是否数组中的数字都为0。

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

349. 两个数组的交集 

初始思路:和上一题一样;

随想录思路:如果存储元素的值没有范围,可以使用set。

class Solution {public int[] intersection(int[] nums1, int[] nums2) {if(nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) return new int[0];Set<Integer> set1 = new HashSet<>(); Set<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(Integer::intValue).toArray();}
}

202. 快乐数 

初始思路:没想到解决思路

随想录思路:首先,只有值重复出现时才会无限循环下去。所以需要判断值是否重复,判断值是否重复就要用到哈希。

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

1. 两数之和

初始思路:暴力遍历数组。

                或者,先把数组转为hashset,然后让目标值减去每一个数,若差值大于0,则判断hashset中有没有这个差值。(找下标代价太大)

随想录思路:使用了hashmap,因为我们需要得到下标,还需要判断对应的值是否存在。

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

鉴于作者水平有限,文章可能存在错误

如有指正,十分感谢

http://www.xdnf.cn/news/769429.html

相关文章:

  • 力扣热题100之对称二叉树
  • flutter开发安卓APP适配不同尺寸的手机屏幕
  • 题目 3225: 蓝桥杯2024年第十五届省赛真题-回文字符串
  • windows11安装编译QtMvvm
  • github 2FA双重认证丢失解决
  • 《操作系统真相还原》——中断
  • AIOps智能运维体系中Python故障预测与根因分析的应用实践
  • EXSI通过笔记本wifi上外网配置
  • Python编程基础(三) | 操作列表
  • 家政维修平台实战12搭建服务详情功能
  • 微型导轨在手术机器人领域中有哪些关键操作?
  • 现代语言模型中的分词算法全解:从基础到高级
  • 1.文件操作相关的库
  • Windows采用npx方式本地部署n8n
  • C#文件压缩与解压缩全攻略:使用ZipFile与ZipArchive实现高效操作
  • `docker run`、`docker start`、`docker exec` 区别
  • 天机学堂-分页查询
  • CodeTop一刷
  • HarmonyOS5 仓颉入门:和 ArkTs 互操作
  • 天机学堂(初始项目)
  • 2024年第十五届蓝桥杯Scratch10月stema选拔赛真题——数字卡片排序
  • 解锁设计师创意魔法:Onlook赋能你的Web创作
  • DAY 40 超大力王爱学Python
  • 20250602在荣品的PRO-RK3566开发板的Android13下打开HDMI显示
  • 深入解析 Python 字符串方法:从基础到高级应用
  • 打开一个新的Maven工程要做的事情
  • (12)-java+ selenium->元素定位大法之By_link_text
  • 吴恩达MCP课程(5):mcp_chatbot_prompt_resource.py
  • InlineHook的原理与做法
  • 每天掌握一个Linux命令 - hping3