L0242. 有效的字母异位词
今天二刷的时候想到思路
如果整个流程比较复杂的话,可以把hsah这一步单独分离出来
示例代码如下
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] countArr = new int[26];
for(int i = 0; i < s.length(); i++){
char sc = s.charAt(i);
char tc = t.charAt(i);
countArr[hashFun(sc)]++;
countArr[hashFun(tc)]--;
}
for(int count : countArr){
if(count != 0) return false;
}
return true;
}
//如果自己想要思路更清晰一点,可以单独把hash函数写出来
public int hashFun(char c){
return c - 'a';
}
L0349. 两个数组的交集
看长度是在1000以内于是还是用了数组,看题解都是用的set。如果用set的话,可以固定一个set然后用set.contains()方法判断。
public int[] intersection(int[] nums1, int[] nums2) {
int[] table1 = new int[1001];
int[] table2 = new int[1001];
for (int num : nums1) {
table1[num] = 1;
}
for (int num : nums2) {
table2[num] = 1;
}
List<Integer> resList = new ArrayList<>();
int index = 0;
while (index < 1001) {
if (table1[index] == 1 && table2[index] == 1) {
resList.add(index);
}
index++;
}
int[] res = new int[resList.size()];
for (int i = 0; i < res.length; i++) {
res[i] = resList.get(i);
}
return res;
}
L0202. 快乐数
很典型的使用 set 判断元素是否存在的场景。
值得注意的是如何获取一个整数的每一个位的数字
public boolean isHappy(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1){
int squareSum = getSquareSum(n);
if (seen.contains(squareSum)){
return false;
}
seen.add(squareSum);
n = squareSum;
}
return true;
}
//n的范围是21亿 平方和最大的数是 1999999999 平方和在int范围内
public int getSquareSum(int n) {
int sum = 0;
while (n != 0) {
int digit = n % 10;
sum = sum + digit * digit;
n = n / 10;
}
return sum;
}
L0001. 两数之和
这道题如果想到HashMap来做的话其实不难,重点在于返回的答案是下边的排列而不是组合,也就是怎么去重的问题。
map(i,j) i是数组中元素的值,j是下标
其实就是for循环把元素装入数组,然后在装入之前判断a是否有对应的b。、
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> idx = new HashMap<>(); // 创建一个空哈希表
for (int j = 0; ; j++) { // 枚举 j
int x = nums[j];
// 在左边找 nums[i],满足 nums[i]+x=target
if (idx.containsKey(target - x)) { // 找到了
return new int[]{idx.get(target - x), j}; // 返回两个数的下标
}
idx.put(x, j); // 保存 nums[j] 和 j
}
}