第一遍
class Solution {public boolean isAnagram(String s, String t) {int[] checkListi = new int[256];int[] checkListj = new int[256];for (int i = 0; i < s.length(); i++) {char checkChar = s.charAt(i);int i_ascii = checkChar - '0';checkListi[i_ascii] += 1;}for (int j = 0; j < t.length(); j++) {char checkChar = t.charAt(j);int j_ascii = checkChar - '0';checkListj[j_ascii] += 1;}return Arrays.equals(checkListi, checkListj);}
}
- 学习set:看到了一篇大佬的文章讲set相关知识的,很厉害。
- 学习set转数组:set如何转换为数组
第一遍
- 思考
- 题目不难,但重点是掌握和了解set相关的知识,包括list、Hashset、treeset
class Solution {public int[] intersection(int[] nums1, int[] nums2) {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();}
}
第一遍
- 思考
- 题目中说了会 无限循环,那么也就是说求和的过程中,sum会重复出现,这对解题很重要!(这一步如果能想出来,才是真的理解题目的,但是我好像是误打误撞了,只是惯性思维觉得应该用set判断是否有重复出现,没有真正读懂题意)
- 题目的重点还是看到是否有出现过,要学会使用set
- 难点:如何取出每一位的数值;这一步想了一下,没有过多思考,答案应该有很简单的方法,就直接看了,自己想了5mins没有很好的办法;
class Solution {public boolean isHappy(int n) {Set<Integer> set1 = new HashSet<>();boolean flag = true;while (flag) {n = sum(n);if (n == 1) {return flag;}flag = set1.add(n);}return flag;}public int sum(int n) {int result = 0;while (n > 0) {int mod = n % 10;result += mod * mod;n /= 10;}return result;}
}
第一遍
- 思考
- 根据建议,先看了题解,了解到了本题应该使用的思路,了解了一下java相关的map的用法,一遍AC了。
- 下面两张图片我感觉是我理解题目的中重点,大家可以好好品一品
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/2b9a8dda12344f7ba2edf1233ef9c679.png)
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/f82fd066f6e24e82bad26a2761de2480.png)
package HashStructure;import java.util.*;public class HashTest {public static void main(String[] args) {int[] nums1 = {2,7,11,15};int target = 9;Solution solution = new Solution();int[] result = solution.twoSum(nums1, target);System.out.println(Arrays.toString(result));}}class Solution {public int[] twoSum(int[] nums, int target) {Map<Integer, Integer> map1 = new HashMap<>();for (int i = 0; i < nums.length; i++) {int findValue = target - nums[i];if (map1.containsKey(findValue)) {return new int[]{i, map1.get(findValue)};} else {map1.put(nums[i], i);}}return new int[]{};}
}