代码随想录一刷-Day05
LeetCode242.有效的字母异位词
如果只有英文字符和数字,可以用数组来做:
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
// 如果不考虑其他中文字符,那当然是用数组做更快
int[] arr = new int[1024];
byte[] sBytes = s.getBytes();
byte[] tBytes = t.getBytes();
for (byte sByte : sBytes) {
arr[sByte]++;
}
for (byte tByte : tBytes) {
arr[tByte]--;
}
for (int j : arr) {
if (j != 0) {
return false;
}
}
return true;
}
时间复杂度: O(n)
空间复杂度: O(1)
如果要考虑 Unicode 字符的话,就不能这样做——中文会出现负数
因此使用 HashMap :
// 对 Unicode 字符的适配方法
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
Map<Character, Integer> table = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
table.put(ch, table.getOrDefault(ch, 0) + 1);
}
for (int i = 0; i < t.length(); i++) {
char ch = t.charAt(i);
table.put(ch, table.getOrDefault(ch, 0) - 1);
if (table.get(ch) < 0) {
return false;
}
}
return true;
}
当然这个方法的效率很差
LeetCode349. 两个数组的交集
由于题目中规定了数组的长度,因此可以使用辅助数组来解决
如果没有规定长度的话,就没办法,只能用 Set 集合了
public int[] intersection(int[] nums1, int[] nums2) {
// 数组长度规定小于1000,对于定长的题目仍可以用数组解法
int[] arr = new int[1000];
for (int i : nums1) {
if (arr[i] > 0) {
continue;
}
arr[i]++;
}
int count = 0;
for (int i : nums2) {
if (arr[i] > 0) {
count++;
arr[i] = -1;
}
}
int[] res = new int[count];
int index = 0;
for (int i : nums2) {
if (arr[i] == -1) {
res[index++] = i;
arr[i] = 1;
}
}
return res;
}
时间复杂度: O(m + n)
空间复杂度: O(n)
LeetCode202. 快乐数
重点在于出现循环的条件——和的结果出现相同数字
public boolean isHappy(int n) {
// 不记得了,能直接解,但是如果不是快乐数就会进入无限循环
// 所以难点在于怎么判断这个数是否会进入无限循环?
// 看了提示,用 Set 集合 —— 进入无限循环则表示,有一个数字重复出现了
// 因此将 sum 的结果放入 Set 集合中,通过判断是否重复出现一个结果来进行循环的跳出
HashSet<Integer> set = new HashSet<>();
int sum = n;
while (sum != 1) {
sum = countSum(sum);
if (set.contains(sum)) {
return false;
}
set.add(sum);
}
return true;
}
private int countSum(int n) {
int sum = 0;
while (n > 0) {
int num = n % 10;
n = n / 10;
sum += num * num;
}
return sum;
}
时间复杂度: O(logn)
空间复杂度: O(logn)
LeetCode1. 两数之和
Classic 的一题
public int[] twoSum(int[] nums, int target) {
// 重温经典一号题目
// 能解很简单,所以直接进阶 —— 时间复杂度低于 O(n^2)
// 这个倒是记得 —— 使用 Map 集合,通过判断当前数字到 target 的差值是否存在于 Map
int[] res = new int[2];
// key 为 nums 里的数组,value 为 对应数字在 nums 的下标
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int sub = target - nums[i];
if (map.containsKey(sub)) {
res[0] = i;
res[1] = map.get(sub);
break;
}
map.put(nums[i], i);
}
return res;
}
时间复杂度: O(n)
空间复杂度: O(n)