代码随想录算法训练营第六天

您所在的位置:网站首页 散列hash算法 代码随想录算法训练营第六天

代码随想录算法训练营第六天

2023-05-21 22:09| 来源: 网络整理| 查看: 265

有效字母的异位词 题目链接

https://programmercarl.com/0242.%E6%9C%89%E6%95%88%E7%9A%84%E5%AD%97%E6%AF%8D%E5%BC%82%E4%BD%8D%E8%AF%8D.html

思路

判断字符是否出现过,就用hash,两个字符串是否出现字符次数相等,分别遍历即可

public boolean isAnagram(String s, String t) { int[] arr = new int[26]; int i = 0; while(i < s.length()) { arr[s.charAt(i++) - 'a']++; } i = 0; while(i < t.length()) { arr[t.charAt(i++) - 'a']--; } for(int num : arr){ if(num!= 0) { return false; } } return true; } 两个数组的交集 题目链接

https://programmercarl.com/0349.%E4%B8%A4%E4%B8%AA%E6%95%B0%E7%BB%84%E7%9A%84%E4%BA%A4%E9%9B%86.html#_349-%E4%B8%A4%E4%B8%AA%E6%95%B0%E7%BB%84%E7%9A%84%E4%BA%A4%E9%9B%86

思路

交集需要去重,且判断是否出现过用hash,所以选择set实现

public int[] intersection(int[] nums1, int[] nums2) { Set set = new HashSet(); Set set1 = new HashSet(); for(int n : nums1) { set.add(n); } for(int n : nums2) { if(set.contains(n)) { set1.add(n); } } return set1.stream().mapToInt(i -> i).toArray(); } } 快乐数 题目链接

https://programmercarl.com/0202.%E5%BF%AB%E4%B9%90%E6%95%B0.html

思路

进入无限循环的条件是,快乐数相同数字结果出现了多次

public boolean isHappy(int n) { Set res = new HashSet(); while(n != 1 && !res.contains(n)) { res.add(n); n = getNextNumber(n); } return n == 1; } private int getNextNumber(int n){ int sum = 0; while(n != 0) { int yushu = n % 10; n = n / 10; sum += yushu * yushu; } return sum; } 两数之和 题目链接

https://programmercarl.com/0001.%E4%B8%A4%E6%95%B0%E4%B9%8B%E5%92%8C.html

思路

从左到右遍历,判断差值是否出现过

public int[] twoSum(int[] nums, int target) { Map map = new HashMap(); for(int i=0;i


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3