第一题 有效的字母异位符
给定两个字符串 s
和 t
,编写一个函数来判断 t
是否是 s
的字母异位词。
注意:若 s
和 t
中每个字符出现的次数都相同,则称 s
和 t
互为字母异位词。
哈希表(字典解法)(数组)
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length())
return false;
// 26个英文字母
int[] record = new int[26];
for (int i = 0; i < s.length(); i++)
record[s.charAt(i) - 'a']++;
for (int i = 0; i < t.length(); i++)
record[t.charAt(i) - 'a']--;
for (int count : record)
if (count != 0)
return false;
return true;
}
}
哈希表(数组)
上个答案的简化
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length())
return false;
// 26个英文字母
int[] record = new int[26];
for (int i = 0; i < s.length(); i++) {
record[s.charAt(i) - 'a']++;
record[t.charAt(i) - 'a']--;
}
for (int count : record)
if (count != 0)
return false;
return true;
}
}
排序
Arrays.sort()方法
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length())
return false;
char[] str1 = s.toCharArray();
char[] str2 = t.toCharArray();
Arrays.sort(str1);
Arrays.sort(str2);
// 比较的是字符数组,而不是字符串
return Arrays.equals(str1, str2);
//return str1.equals(str2);
//return str1 == str2;
}
}
第二题 赎金信
给你两个字符串:ransomNote
和 magazine
,判断 ransomNote
能不能由 magazine
里面的字符构成。
如果可以,返回 true
;否则返回 false
。
magazine
中的每个字符只能在 ransomNote
中使用一次。
(和第一题差不多)
哈希表
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
if (ransomNote.length() > magazine.length())
return false;
int[] record = new int[26];
for (int i = 0; i < ransomNote.length(); i++)
record[ransomNote.charAt(i) - 'a']++;
for (int i = 0; i < magazine.length(); i++)
record[magazine.charAt(i) - 'a']--;
// 错误:for (int n : record)
// 增强型for循环用于遍历数组或集合中的元素,而不是遍历数组的索引
for (int i = 0; i < record.length; i++)
if (record[i] > 0)
return false;
return true;
}
}
第三题 字母异位词分组
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
大佬解法(一行代码)
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
return new ArrayList<>(Arrays.stream(strs).collect(Collectors.groupingBy(s -> Arrays.toString(s.codePoints().sorted().toArray()))).values());
}
}
排序
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
// 存储排序后的字符串作为key,原始字符串列表作为value
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
char[] array = str.toCharArray();
Arrays.sort(array);
// 将排序后的字符数组转换回字符串,作为key
String key = new String(array);
// 从map中获取key对应的字符串列表,如果不存在则创建一个新的列表
List<String> list = map.getOrDefault(key, new ArrayList<String>());
list.add(str);
map.put(key, list);
}
// 将map中的值(即多条列表)转换为一个列表并返回
return new ArrayList<List<String>>(map.values());
}
}
计数
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String str : strs) {
int[] counts = new int[26];
for (int i = 0; i < str.length(); i++)
counts[str.charAt(i) - 'a']++;
// 将每个出现次数大于 0 的字母和出现次数按顺序拼接成字符串,作为哈希表的键
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 26; i++)
if (counts[i] != 0) {
sb.append((char) ('a' + i));
// 避免重复元素导致的错误
sb.append(counts[i]);
}
String key = sb.toString();
List<String> list = map.getOrDefault(key, new ArrayList<String>());
list.add(str);
map.put(key, list);
}
return new ArrayList<List<String>>(map.values());
}
}
第四题 找到字符串中的所有字母异位词
给定两个字符串 s
和 p
,找到 s
中所有 p
的 异位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。
异位词 指由相同字母重排列形成的字符串(包括相同的字符串)。
滑动窗口
class Solution {
public List<Integer> findAnagrams(String s, String p) {
if (s.length() < p.length())
return new ArrayList<Integer>();
int[] countS = new int[26];
int[] countP = new int[26];
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < p.length(); i++) {
countS[s.charAt(i) - 'a']++;
countP[p.charAt(i) - 'a']++;
}
if (Arrays.equals(countS, countP))
ans.add(0);
for (int i = 0; i < s.length() - p.length(); i++) {
// 窗口右滑
countS[s.charAt(i) - 'a']--;
countS[s.charAt(i + p.length()) - 'a']++;
if (Arrays.equals(countS, countP))
ans.add(i + 1);
}
return ans;
}
}
变长窗口
class Solution {
public List<Integer> findAnagrams(String s, String p) {
if (s.length() < p.length())
return new ArrayList<Integer>();
int[] count = new int[26];
for (char c : p.toCharArray())
count[c - 'a']++;
// 左窗 右窗
int l = 0, r = 0;
List<Integer> ans = new ArrayList<>();
// 开始时count已保存有p的所有字母
while (r < s.length())
// 遇到count元素右窗右移并消耗
if (count[s.charAt(r) - 'a'] > 0) {
count[s.charAt(r++) - 'a']--;
// 消耗够了,即窗口内的元素等于p,记录
if (r - l == p.length())
ans.add(l);
} else // 非count内元素,右移左窗并补充
count[s.charAt(l++) - 'a']++;
return ans;
}
}
第五题 两个数组的交集
给定两个数组 nums1
和 nums2
,返回 它们的
交集
。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。
哈希表(HashSet)
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0)
return new int[0];
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for (int n : nums1)
set1.add(n);
for (int n : nums2)
if (set1.contains(n))
set2.add(n);
int[] arr = new int[set2.size()];
int count = 0;
for (int i : set2)
arr[count++] = i;
return arr;
}
}
哈希表(数组)
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0)
return new int[0];
Set<Integer> set = new HashSet<>();
int[] hash1 = new int[1001];
int[] hash2 = new int[1001];
for (int i : nums1)
hash1[i]++;
for (int i : nums2)
hash2[i]++;
for (int i = 0; i < 1001; i++)
if (hash1[i] > 0 && hash2[i] > 0)
set.add(i);
int[] arr = new int[set.size()];
int count = 0;
for (int i : set)
arr[count++] = i;
return arr;
}
}
排序(双指针)
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
// 求最长长度
int length = nums1.length > nums2.length ? nums1.length : nums2.length;
int[] res = new int[length];
int count = 0, i1 = 0, i2 = 0;
while (i1 < nums1.length && i2 < nums2.length)
if (nums1[i1] == nums2[i2]) {
// 输出不要重复的数
if (count == 0 || nums1[i1] != res[count - 1])
res[count++] = nums1[i1];
i1++;
i2++;
} else if (nums1[i1] > nums2[i2])
i2++;
else
i1++;
return Arrays.copyOfRange(res, 0, count);
}
}
第六题 快乐数
编写一个算法来判断一个数 n
是不是快乐数。
「快乐数」 定义为:
- 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
- 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
- 如果这个过程 结果为 1,那么这个数就是快乐数。
如果 n
是 快乐数 就返回 true
;不是,则返回 false
。
哈希表(set)
思路:题目提到会无线循环,即n会重复出现
class Solution {
public boolean isHappy(int n) {
Set<Integer> record = new HashSet<>();
while (n != 1 && !record.contains(n)) {
record.add(n);
n = getNext(n);
}
return n == 1;
}
private int getNext(int n) {
int res = 0;
while (n > 0) {
int temp = n % 10;
res += temp * temp;
n = n / 10;
}
return res;
}
}
快慢指针法
快指针相对于慢指针每次多走一格
class Solution {
public boolean isHappy(int n) {
int slow = n;
int fast = getNext(n);
while (fast != 1 && slow != fast) {
slow = getNext(slow);
fast = getNext(getNext(fast));
}
return fast == 1;
}
private int getNext(int n) {
int res = 0;
while (n > 0) {
int temp = n % 10;
res += temp * temp;
n = n / 10;
}
return res;
}
}
第七题 两数之和
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
暴力解法
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++)
for (int j = i + 1; j < nums.length; j++)
if (nums[i] + nums[j] == target)
return new int[]{i, j};
return new int[]{0};
}
}
哈希表(map)
使用数组和set做哈希表的局限:
数组大小受限制,并且可能造成空间浪费
set是单列集合,里面只能放一个key
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];
if (map.containsKey(temp)) {
res[1] = i;
res[0] = map.get(temp);
break;
}
map.put(nums[i], i);
}
return res;
}
}
第八题 四数相加2
给你四个整数数组 nums1
、nums2
、nums3
和 nums4
,数组长度都是 n
,请你计算有多少个元组 (i, j, k, l)
能满足:
0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
哈希表(map)
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
int res = 0;
Map<Integer, Integer> map = new HashMap<>();
// 统计所有1,2数组元素之和,并记录出现次数
for (int i : nums1)
for (int j : nums2)
map.put(i + j, map.getOrDefault(i + j, 0) + 1);
// 统计所有3,4数组元素和为前面的(i+j)的相反数的次数
for (int i : nums3)
for (int j : nums4)
res += map.getOrDefault(-(i + j), 0);
return res;
}
}
第九题 三数之和
给你一个整数数组 nums
,判断是否存在三元组 [nums[i], nums[j], nums[k]]
满足 i != j
、i != k
且 j != k
,同时还满足 nums[i] + nums[j] + nums[k] == 0
。请
你返回所有和为 0
且不重复的三元组。
注意:答案中不可以包含重复的三元组。
哈希表(set)
用时太长
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
// 排序
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
// 若第一个元素大于0,则直接返回
if (nums[i] > 0)
return res;
// 三元组元素a去重
// 不能写nums[i] == nums[i + 1],否则例如[-1, -1, 2]会漏掉
if (i > 0 && nums[i] == nums[i - 1])
continue;
HashSet<Integer> set = new HashSet<>();
for (int j = i + 1; j < nums.length; j++) {
// 三元组元素b去重
// 两数相等还有机会,三数相等除非全为0,否则没有机会
if (j > i + 2 && nums[j] == nums[j - 1] && nums[j - 1] == nums[j - 2])
continue;
// 三元组元素c去重
if (set.contains(-(nums[i] + nums[j]))) {
res.add(Arrays.asList(nums[i], nums[j], -(nums[i] + nums[j])));
set.remove(-(nums[i] + nums[j]));
} else
set.add(nums[j]);
}
}
return res;
}
}
双指针法
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
// 排序
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
// 若第一个元素大于0,则直接返回
if (nums[i] > 0)
return res;
// a去重
if (i > 0 && nums[i] == nums[i - 1])
continue;
// a -> nums[i] b -> nums[l] c -> nums[r]
int l = i + 1;
int r = nums.length - 1;
while (r > l) {
int sum = nums[i] + nums[l] + nums[r];
if (sum > 0)
r--;
else if (sum < 0)
l++;
else { // 满足题意
res.add(Arrays.asList(nums[i], nums[l], nums[r]));
// 对b和c去重
while (r > l && nums[r] == nums[r - 1])
r--;
while (l < r && nums[l] == nums[l + 1])
l++;
r--;
l++;
}
}
}
return res;
}
}
第十题 四数之和
给你一个由 n
个整数组成的数组 nums
,和一个目标值 target
。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]]
(若两个四元组元素一一对应,则认为两个四元组重复):
0 <= a, b, c, d < n
a
、b
、c
和d
互不相同nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。
双指针法
(和第七题一个思路)
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
// 排序
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
// 若第一个元素大于0且大于target,则直接返回
// 负数和零不符合,比如4个0加起来还是0,4个-1加起来是-4小于-1
if (nums[i] > 0 && nums[i] > target)
return res;
// a去重
if (i > 0 && nums[i] == nums[i - 1])
continue;
// a -> nums[i] b -> nums[j] c -> nums[l] d -> nums[r]
for (int j = i + 1; j < nums.length; j++) {
// b去重
if (j > i + 1 && nums[j] == nums[j - 1])
continue;
int l = j + 1, r = nums.length - 1;
while (r > l) {
long sum = (long)nums[i] + nums[j] + nums[l] + nums[r];
if (sum > target)
r--;
else if (sum < target)
l++;
else { // 满足题意
res.add(Arrays.asList(nums[i], nums[j], nums[l], nums[r]));
// 对c和d去重
while (r > l && nums[r] == nums[r - 1])
r--;
while (l < r && nums[l] == nums[l + 1])
l++;
r--;
l++;
}
}
}
}
return res;
}
}