242.有效的字母异位词 leetcode.com/problems/va…
思路: 最好想的还是暴力两个for循环,O(N^2)
class Solution {
public boolean isAnagram(String s, String t) {
int[] record = new int[26];
for (int i = 0; i < s.length(); i++) {
// 把s中的字符的ascii映射到record数组中,比如 s - a 就有一个对应的数字
record[s.charAt(i) - 'a']++;
}
// 如果在t中出现过这个字符就减少record
for (int i = 0; i < t.length(); i++) {
record[t.charAt(i) - 'a']--;
}
// record数组如果有的元素不为零0,说明s或者t的字符数量不一样
for (int count: record) {
if (count != 0) {
return false;
}
}
return true;
}
}
- 两个数组的交集 leetcode.com/problems/in…
思路:这道题因为数据是有范围的,所以可以用数组作为哈希表,这样性能更好点 这道题用HashSet的话就很简单了,因为set集合是不能加入重复元素的
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
return new int[0];
}
Set<Integer> set1 = new HashSet<>();
Set<Integer> result = new HashSet<>();
//遍历数组1
for (int i : nums1) {
set1.add(i);
}
//遍历数组2的过程中判断哈希表中是否存在该元素
for (int i : nums2) {
if (set1.contains(i)) {
result.add(i);
}
}
//将结果集合转为数组
return result.stream().mapToInt(x -> x).toArray();
}
}
- 快乐数 leetcode.com/problems/ha… 思路就是:用HashSet去判断这个数会不会重复,如果重复了那就会无限循环了
class Solution {
public boolean isHappy(int n) {
Set<Integer> record = new HashSet<>();
// 查找HashSet中有没有重复的数
while (n != 1 && !record.contains(n)) {
record.add(n);
n = getNextNumber(n);
}
return n == 1;
}
// 获得个位和十位数的平方和
private int getNextNumber(int n) {
int res = 0;
while (n > 0) {
int temp = n % 10;
res += temp * temp;
n = n / 10;
}
return res;
}
}
- 两数之和 leetcode.com/problems/tw… 思路:用HashMap来记录访问过的元素和对应的下标,在循环中,通过HashMap来快速判断是否有需要的元素
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
if (nums == null || nums.length == 0) {
return res;
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int temp = target - nums[i];
// 在map中找是否有需要的元素
if (map.containsKey(temp)) {
res[1] = i;
res[0] = map.get(temp);
break;
}
map.put(nums[i], i); // 如果没找到匹配对,就把访问过的元素和下标加入到map中
}
return res;
}
}