当前位置: 首页 > 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.lqws.cn/news/83773.html

相关文章:

  • 【看到哪里写到哪里】C的指针-3(函数指针)
  • TC3xx学习笔记-启动过程详解(一)
  • Arch安装botw-save-state
  • deep forest安装及使用教程
  • 一步一步配置 Ubuntu Server 的 NodeJS 服务器详细实录——4. 配置服务器终端环境 zsh , oh my zsh, vim
  • 基于爬取的典籍数据重新设计前端界面
  • 前端八股之CSS
  • 推荐一款使用html开发桌面应用的工具——mixone
  • 力扣HOT100之多维动态规划:62. 不同路径
  • 力扣HOT100之多维动态规划:64. 最小路径和
  • 量子物理:深入学习量子物理的基本概念与应用
  • Python_day43
  • Linux运维笔记:服务器感染 netools 病毒案例
  • mysql专题上
  • Vue 项目创建教程 (开发前的准备工作保姆级辅助文档)
  • 专注成就技术传奇:一路向前的力量
  • 数学建模期末速成 最短路径
  • Ubuntu22.04 安装 ROS2 Humble
  • Spark-TTS: AI语音合成的“变声大师“
  • ubuntu 添加应用到启动菜单
  • P5684 [CSP-J2019 江西] 非回文串 题解
  • Webpack依赖
  • Android高级开发第四篇 - JNI性能优化技巧和高级调试方法
  • 网络攻防技术三:网络脆弱性分析
  • 高阶数据结构——并查集
  • C语言基础(10)【二维数组 字符数组 字符串相关操作】
  • DAY01:【ML 第三弹】基本概念和建模流程
  • pytorch基本运算-范数
  • SCAU8640--希尔排序
  • 【知识点】第3章:基本数据类型