242.有效的字母异位词
题目链接:https://leetcode.cn/problems/valid-anagram/
思路
- 将字符串的各位存储到Map集合中,最后判断两个Map集合是否相等。时间O(n),空间O(1)
- 将字符串的各位转换为数字后存储到int数组中,最后判断数组各位元素是否都等于0。时间O(n),空间O(1)
代码
//Map
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
Map<Character, Integer> map1 = new HashMap<>();
Map<Character, Integer> map2 = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
map1.put(s.charAt(i), map1.getOrDefault(s.charAt(i), 0) + 1);
}
for (int i = 0; i < t.length(); i++) {
map2.put(t.charAt(i), map2.getOrDefault(t.charAt(i), 0) + 1);
}
return map1.equals(map2);
}
}
//数组
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] arr = new int[26];
for (int i = 0; i < s.length(); i++) {
arr[s.charAt(i) - 'a']++;
}
for (int i = 0; i < t.length(); i++) {
arr[t.charAt(i) - 'a']--;
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
return false;
}
}
return true;
}
}
349. 两个数组的交集
题目链接:https://leetcode.cn/problems/intersection-of-two-arrays/
思路
利用Set集合的去重效果。时间O(m+n),空间O(min{m,n})
代码
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> res = new HashSet<>();
Set<Integer> set = new HashSet<>();
for (int i = 0; i < nums1.length; i++) {
set.add(nums1[i]);
}
for (int i = 0; i < nums2.length; i++) {
if (set.contains(nums2[i])) {
res.add(nums2[i]);
}
}
//将set转换为数组
return res.stream().mapToInt(x -> x).toArray();
}
}
202. 快乐数
题目链接:https://leetcode.cn/problems/happy-number/
思路
利用Set存储sum,如果sum重复出现返回false。时空复杂度俺不会???
代码
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
int sum = 0;
while (sum != 1) {
sum = 0;
while (n != 0) {
sum += (n % 10) * (n % 10);
n /= 10;
}
if (set.contains(sum)) {
return false;
}
set.add(sum);
n = sum;
}
return true;
}
}
1. 两数之和
题目链接:https://leetcode.cn/problems/two-sum/
思路
- 暴力双循环。时间O(n^2),空间O(1)
- 利用Map集合。key-value存储数组元素-该元素的下标。时间O(n),空间O(n)
代码
//Map
class Solution {
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 null;
}
}