LeetCode242 有效的字母异位词
public class code242 {
public boolean isAnagram(String s, String t) {
// 定义一个数组用来存储每个字符出现的次数
int[] store = new int[26];
for (int i = 0; i < s.length(); i++) {
store[s.charAt(i) - 'a']++;
}
for (int i = 0; i < t.length(); i++) {
store[t.charAt(i) -'a']--;
}
// 遍历store数组,如果元素都是零则返回true
for (int i = 0; i < store.length; i++) {
if (store[i] != 0) {
return false;
}
}
return true;
}
}
使用哈希数组的原因是数据量是有限的
LeetCode349 两个数组的交集
题目链接: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代码:
public class code349 {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> num1 = new HashSet<>();
Set<Integer> res = new HashSet<>();
// 将nums1中的元素添加到哈希表当中
for (int i = 0; i < nums1.length; i++) {
num1.add(nums1[i]);
}
// 判断是否有相同元素,有的话添加到结果集合中
for (int i = 0; i < nums2.length; i++) {
if (num1.contains(nums2[i])) {
res.add(nums2[i]);
}
}
int[] res1 = new int[res.size()];
int j = 0;
for (Integer i : res) {
res1[j++] = i;
}
return res1;
}
使用HashSet,不要忘了函数的返回值是数组,最后将集合转为数组
LeetCode202 快乐数
题目链接:https://programmercarl.com/0202.%E5%BF%AB%E4%B9%90%E6%95%B0.html
代码:
public class code202 {
public boolean isHappy(int n) {
Set<Integer> 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 temp = n % 10;
sum += temp * temp;
n = n / 10;
}
return sum;
}
跟上一题类似,只不过这道题先写一个函数用来获取下一个num的值
LeetCode1 两数之和
题目链接:https://programmercarl.com/0001.%E4%B8%A4%E6%95%B0%E4%B9%8B%E5%92%8C.html
代码:
public class code1 {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
return new int[]{map.get(target - nums[i]), i};
}
map.put(nums[i], i);
}
return new int[0];
}
}
使用HashMap存储键值对,要搞清楚键和值分别对应什么