Leetcode242. 有效的字母异位词
注意:√
- 主要是哈希表那个找到对应索引的思想
- 学习一下这个字符相减的写法
- 回忆java的自动类型转换
public boolean isAnagram(String s, String t) {
int[] arrs = new int[26];
int[] arrt = new int[26];
for (char c : s.toCharArray()) {
int num = c - 'a';
arrs[num]++;
}
for (char c : t.toCharArray()) {
int num = c - 'a';
arrt[num]++;
}
for (int i = 0; i < 26; i++) {
if (arrs[i] != arrt[i]){
return false;
}
}
return true;
}
Leetcode349. 两个数组的交集
注意:×
- 学习使用HashSet
- 注意这里不需要转int为Integer,会自动帮你处理
- 学习一下这个写法
return resSet.stream().mapToInt(x -> x).toArray();
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length ==0 || nums2.length ==0) {
return new int[0];
}
HashSet<Integer> set1 = new HashSet<Integer>();
HashSet<Integer> setAns = new HashSet<Integer>();
for (int i : nums1) {
set1.add(i);
}
for (int i : nums2) {
if (set1.contains(i)){
setAns.add(i);
}
}
//方法2:另外申请一个数组存放setRes中的元素,最后返回数组
int[] arr = new int[setAns.size()];
int j = 0;
for(int i : setAns){
arr[j++] = i;
}
return arr;
}
Leetcode202. 快乐数
注意:√
- 一遍过,这个快乐数的定义楞了一下,太呆了
- 梦回大一回文数
public boolean isHappy(int n) {
HashSet<Integer> resultSet = new HashSet<>();
while (n != 1 && !resultSet.contains(n)) {
resultSet.add(n);
n = getNextNumber(n);
}
return n==1?true:false;
}
private int getNextNumber(int n) {
int res = 0;
while (n!= 0) {
int a = n%10;
res = res+a*a;
n=n/10;
}
return res;
}
Leetcode1. 两数之和
注意:×
- 这一题的哈希方式取得非常巧妙,做了一个HashMap进行维护
- 注意生成数组的写法,
[]
里面放的是大小,直接指定元素应该是new int[]{i, hm.get(a)}
这样写
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> hm = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int a = target - nums[i];
if (hm.containsKey(a)) {
// return new int[i, hm.get(a)];
return new int[]{i, hm.get(a)};
}
hm.put(nums[i], i);
}
return null;
}