代码随想录算法训练营第五天

发布时间 2023-09-11 20:08:29作者: 昼阳Helios

代码随想录算法训练营第五天 | LeetCode 242(有效的字母异位词) LeetCode 349(两个数组的交集) LeetCode 202(快乐数) LeetCode 1(两数之和)

242:有效的字母异位词

LeetCode 242(有效的字母异位词)

class Solution {
    public boolean isAnagram(String s, String t) {
        int length = s.length();
        if(length != t.length()){
            return false;
        }
        //构建一个长度为26的数组
        int[] count = new int[26];
        for(int i = 0; i < length; i++){
            //维护count数组
            count[s.charAt(i) - 'a']++;
            count[t.charAt(i) - 'a']--;
        }
        //遍历count数组 如果有的元素不为零0,说明字符串s和t一定是谁多了字符或者谁少了字符,return false
        for(int i = 0; i < count.length; i++){
            if(count[i] != 0){
                return false;
            }
        }
        return true;
    }
}

349:两个数组的交集

LeetCode 349(两个数组的交集)

import java.util.HashSet;
import java.util.Set;
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<Integer>();
        Set<Integer> res = new HashSet<Integer>();
        //遍历nums1
        for (int num : nums1) {
            set.add(num);
        }
        //遍历nums2
        for (int num : nums2) {
            //判断set是否含有当前num 含有则表示该元素同时出现在了两个数组中 即为交集
            if (set.contains(num)) {
                res.add(num);
            }
        }
        return res.stream().mapToInt(x -> x).toArray();
    }
}

202:快乐数

LeetCode 202(快乐数)

import java.util.HashSet;
import java.util.Set;
class Solution {
    public boolean isHappy(int n) {
        Set<Integer> set = new HashSet<>();
        int temp;
        int i;
        while ( n != 1 && !set.contains(n)){
            set.add(n);
            temp = 0;
            i = n;
            //模拟求平方和
            while(i > 0){
                temp += (i % 10)*(i % 10);
                i = i / 10;
            } 
            n = temp;
        }
        return n == 1;
    }
}

1:两数之和

LeetCode 1(两数之和)

import java.util.HashMap;
import java.util.Map;
class Solution {
    public int[] twoSum(int[] nums, int target) {
        //使用map存储 
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            //边遍历边寻找
            if(map.containsKey(nums[i])){
                return new int[]{i,map.get(nums[i])};
            }
            map.put(target - nums[i],i);
        }
        return null;
    }
}