242. 有效的字母异位词
题目:242. 有效的字母异位词 - 力扣(LeetCode)
状态:AC
扩展题目
49.字母异位词分组(字符串排序后作为键,注意char[]转String可以new String(char[]))
438.找到字符串中所有字母异位词
思路
注意:如果使用Map的话,添加元素的方法是put()
代码
时间复杂度:O(n+m) 空间复杂度:O(1)
class Solution {
public boolean isAnagram(String s, String t) {
int[] num = new int[26];
for (char c : s.toCharArray()) {
num[c - 'a']++;
}
for (char c : t.toCharArray()) {
num[c - 'a']--;
}
for (int n : num) {
if (n != 0)
return false;
}
return true;
}
}
349. 两个数组的交集
题目:349. 两个数组的交集 - 力扣(LeetCode)
状态:AC
思路
注意:两个哈希表,可以这样遍历set:for(int num : set)
代码
时间复杂度:O(n+m) 空间复杂度:O(n+k)
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Set<Integer> res = new HashSet<>();
for(int num : nums1){
set.add(num);
}
for(int num : nums2){
if(set.contains(num)){
res.add(num);
}
}
int[] ans = new int[res.size()];
int j = 0;
for(int i : res){
ans[j++] = i;
}
return ans;
}
}
202. 快乐数
状态:位转换卡壳了
思路
关键条件:无限循环 但始终变不到 1,表示中间可能会有重复值出现。
注意:位转换
代码
时间复杂度:O(n) 空间复杂度:O(1)
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while (n != 1) {
if(set.contains(n)){
return false;
}
set.add(n);
n = nextNum(n);
}
return true;
}
public int nextNum(int n){
int res = 0;
while(n > 0){
res += (n % 10) * (n % 10);
n = n / 10;
}
return res;
}
}
1. 两数之和
状态:AC
思路
注意:HashMap存target-nums[i]就行了
代码
时间复杂度:O(n) 空间复杂度:O(n)
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> hMap = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++){
if(hMap.containsKey(target - nums[i])){
return new int[] {i, hMap.get(target - nums[i])};
}
hMap.put(nums[i], i);
}
return new int[0];
}
}