代码随想录Day06
242.有效的字母异位词
- 根据题意要符合条件,至少两个字符串长度相等,所以先确认二者长度是否相等,不等直接false
- 相等,定义一个26字母的计数数组
- 遍历字符串s和t,计数时:s中的字母 +1,t中的字符 -1
- 最后判断计数数组是否全为零,若不全为零则false
class Solution {
public boolean isAnagram(String s, String t) {
//如果两个字符串长度不相等那么它们一定不符合题意
if(s.length() != t.length()){
return false;
}
//定义一个字母数组,存储每个字母出现的次数
//charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1
int[] nums = new int[26];
for(int i=0;i<s.length();i++){
nums[s.charAt(i) - 'a']++; //s中的每个字符,增加数组中每个字母对应计数
nums[t.charAt(i) - 'a']--; //减少数组中每个字母对应计数
}
//校验nums数组中是否存在非零值,若存在则不符合条件
for(int i=0;i<26;i++){
if(nums[i] != 0){
return false;
}
}
return true;
}
}
349.两个数组的交集
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
//定义两个HashSet对象(利用HashSet自动去重的特性)
Set<Integer> set1=new HashSet<>();
Set<Integer> set2=new HashSet<>();
//将nums1放入set1中
for(int num : nums1){
set1.add(num);
}
//遍历nums2,将二者交集放入set2中
for(int num : nums2){
if(set1.contains(num)){
set2.add(num);
}
}
//将set2转换为int数组,然后return
int[] intArray = new int[set2.size()];
int index = 0;
for (Integer num : set2) {
intArray[index++] = num;
}
return intArray;
}
}
202.快乐数
哈希表
class Solution {
//计算快乐数
private int Sum(int n){
int sum = 0;
while(n>0){
int m=n%10;
sum += m * m;
n /= 10;
}
return sum;
}
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while(n != 1 && !set.contains(n)){
set.add(n);
n = Sum(n);
}
return n == 1;
}
}
双指针
“快指针” 每次走两步,“慢指针” 每次走一步,若两个指针最后能相遇,则说明这个数组存在循环,不符合快乐数的要求;
public class Solution {
// 计算快乐数的值
private int Sum(int n) {
int sum = 0;
while (n > 0) {
int m = n % 10;
sum += m * m;
n /= 10;
}
return sum;
}
// 判断一个数是否为快乐数
public boolean isHappy(int n) {
// 定义快慢指针,初始时都指向n
int slow = n;
int fast = Sum(n);
// 当fast不等于1,且slow和fast不相遇(即未进入循环)时继续循环
while (fast != 1 && slow != fast) {
slow = Sum(slow); // 慢指针每次移动一步
fast = Sum(Sum(fast)); // 快指针每次移动两步
}
// 如果fast等于1,说明找到了快乐数,返回true;否则返回false
return fast == 1;
}
}
1.两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
//定义一个value-key的哈希表
HashMap<Integer,Integer> HashSet = new HashMap<>();
//遍历数组
for(int i=0;i<nums.length;i++){
//need是与当前数互补的值
int need = target - nums[i];
//检查哈希表中是否存在need
if(HashSet.containsKey(need)){
//若存在,返回结果
return new int[]{HashSet.get(need),i};
}
//不存在,将value值,及其key存入我们的哈希表中
HashSet.put(nums[i],i);
}
//若没有符合条件的数,则返回null
return null;
}
}