代码随想录算法训练营第6天|字母异位词、数组交集、快乐数

快速判断一个元素是否出现集合里的时候,就要考虑哈希法

lc242有效的字母异位词

思路

统计原字符串各字母出现频率,如果新字符串使得集合中所有字母频率归零,则是字母异位词

代码

class Solution {
    public boolean isAnagram(String s, String t) {
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++){
            Character ch = s.charAt(i);
            map.put(ch, map.getOrDefault(ch, 0) + 1);
        }
        for (int i = 0; i < t.length(); i++){
            Character ch = t.charAt(i);
            if (map.getOrDefault(ch, 0) == 0){
                return false;
            }
            map.put(ch, map.get(ch) - 1);
        }
        for (int temp : map.values()){
            if (temp != 0){
                return false;
            }
        }
        return true;
    }
}

lc349两个数组的交集

思路

一个HashSet存一个数组的元素,一个HashSet在遍历另一个数组时保存不重复的交集

代码

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet<>();
        Set<Integer> resList = new HashSet<>();
        for (int i = 0; i < nums1.length; i++){
            set.add(nums1[i]);
        }
        for (int i = 0; i < nums2.length; i++){
            if (set.contains(nums2[i])){
                resList.add(nums2[i]);
            }
        }
        int index = 0;
        int res[] = new int[resList.size()];
        for(int i:resList){
            res[index++] = i;
        }
        return res;
    }
}

lc202快乐数

思路

无限循环时注意及时退出,使用set来快速判断是否出现过n

代码

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> record = new HashSet<>();
        while (n != 1 && !record.contains(n)){
            record.add(n);
            int sum = 0;
            while (n != 0){
                int num = n % 10;
                sum += num * num;
                n = n / 10;
            }
            n = sum;
        }
        return n==1;
    }
}

lc1两数之和

思路

边遍历边看另一个元素(和-当前元素)是否已经存在,不存在把当前元素添加到HashMap中

代码

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i=0; i < nums.length; i++){
            if (map.containsKey(target-nums[i])){
                return new int[]{i, map.get(target-nums[i])};
            } else{
                map.put(nums[i], i);
            }
        }
        return new int[]{};
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务