目录
242 有效的字母异位词
该题与383 赎金信思路相同
需要判断字符串s与字符串t中每个字符出现的次数是否相同,我们很自然想到通过哈希进行处理。
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length() != t.length())return false;
int cnt[] = new int[26];
for(int i = 0;i < s.length();i++){
cnt[s.charAt(i) - 'a']++;
}
for(int i = 0;i < t.length();i++){
cnt[t.charAt(i) - 'a']--;
}
for(int i = 0;i < 26;i++){
if(cnt[i] != 0)return false;
}
return true;
}
}
时间复杂度O(n),空间复杂度O(1)。
349 两个数组的交集
设置Set<Integer> set 与 res,通过set记录nums1中元素,res则通过contains方法记录nums1与nums2共有元素,最后将res中元素以数组的形式进行返回。
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> set = new HashSet<>();
Set<Integer> res = new HashSet<>();
for(int o : nums1){
set.add(o);
}
for(int o : nums2){
if(set.contains(o)){
res.add(o);
}
}
return res.stream().mapToInt(x -> x).toArray();
}
}
时间复杂度O(n),空间复杂度O(n) 。
202 快乐数
先定义cal方法,进行题目所描述的计算。由题目描述 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到1 可知在运算过程中有变成1或者进行无限循环两种情况,由此我们定义Set<Integer>res 存储cal方法计算得来的元素,并设置while的循环条件为n不为1(此时判定该数满足要求为快乐数)并且计算得来的n为res未出现过的元素(此时尚不能判断n是否为快乐数,如果res中出现过n则已经进入了无限循环的情况,可以判断不是快乐数)。
class Solution {
public boolean isHappy(int n) {
Set<Integer>res = new HashSet<>();
while(n != 1 && !res.contains(n)){
res.add(n);
n = cal(n);
}
return n == 1;
}
private int cal(int num){
int sum = 0;
while(num > 0){
int temp = num % 10;
num /= 10;
sum += temp * temp;
}
return sum;
}
}
时间复杂度O(logn),空间复杂度O(logn)。
1 两数之和
题目要求我们在nums数组中找到两个和为target的数并返回他们的下标。
我们可以通过暴力搜索的方法枚举nums中的int元素num并搜索是否存在target - num,时间复杂度O(n^2),空间复杂度O(1)。
也可以通过哈希法进行处理,已知我们要返回下标,则可以定义Map<Integer,Integer> mp,让mp的键保存num的值,mp的值保存num在数组中的下标,通过mp.constainKey()方法检测是否存在相 应值,节约了时间。
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> mp = new HashMap<>();
for(int i = 0;i < nums.length;i++){
int temp = target - nums[i];
if(mp.containsKey(temp)){
res[0] = i;
res[1] = mp.get(temp);
break;
}
mp.put(nums[i],i);
}
return res;
}
}
该方法只遍历了一次nums数组 。
时间复杂度O(n),空间复杂度O(n)。