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

代码随想录第六天

242.有效的字母异位词

242. 有效的字母异位词 - 力扣(LeetCode)

采用数组来记录出现的次数,一个++,一个--,如果最后都为0则返回true

class Solution {public boolean isAnagram(String s, String t) {int[] record = new int[26];for (char c : s.toCharArray()) {record[c - 'a']++;}for (char c : t.toCharArray()) {record[c - 'a']--;}for (int count : record) {if (count != 0) {return false;}}return true;}
}

349. 两个数组的交集

349. 两个数组的交集 - 力扣(LeetCode)

双指针方法:

class Solution {public int[] intersection(int[] nums1, int[] nums2) {Set<Integer> set = new HashSet<>();Arrays.sort(nums1);Arrays.sort(nums2);int i = 0, j = 0;while (i < nums1.length && j < nums2.length) {if (nums1[i] == nums2[j]) {set.add(nums1[i]);i++;j++;} else if (nums1[i] > nums2[j])j++;elsei++;}int[] res = new int[set.size()];int index = 0;for (int num : set) {res[index++] = num;}return res;}
}

HashSet方法:

class Solution {public int[] intersection(int[] nums1, int[] nums2) {Set<Integer> n1 = new HashSet<>();Set<Integer> n2 = new HashSet<>();for (int i : nums1) {n1.add(i);}for (int i : nums2) {if (n1.contains(i))n2.add(i);}int[] res = new int[n2.size()];int i = 0;for (int j : n2) {res[i++] = j;}return res;}
}

202. 快乐数 19:38min

202. 快乐数 - 力扣(LeetCode)

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

1. 两数之和

1. 两数之和 - 力扣(LeetCode)

面试变形:Leetcode 01 两数之和 面试变形-CSDN博客

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


http://www.mrgr.cn/news/7279.html

相关文章:

  • 四、Centos7-安装Gitlab
  • 饿了么后端登录模块
  • 基于cubemx的STM32的freertos的串口通信
  • 数据结构之 队列入门 队列例程 队列例程分析
  • Vue中的methods方法与computed计算属性的区别
  • RTC碰到LXTAL低频晶振停振怎么办?
  • Java 中的 Tomcat 详解
  • mac苹果电脑搭建Python开发环境
  • StarRocks 存算分离数据回收原理
  • ZooKeeper的8大应用场景解析
  • SLAM学习笔记
  • DNS服务器的起点:根服务器
  • c语言利用if else制作信号灯程序
  • Elementui-Plus动态渲染图标icon
  • SQL Server中如何自动抓取阻塞
  • 分享一个基于python的租房数据分析与可视化系统Hadoop大数据源码(源码、调试、LW、开题、PPT)
  • 多模态大模型技术详解(图像分块、特征对齐)
  • 排序算法【快速排序】
  • jQuery实现前端下载功能
  • 医疗器械网络安全