算法训练营第六天|242.有效的字母异位词、349. 两个数组的交集、202. 快乐数、1. 两数之和

59 阅读1分钟

第五天是周日休息。

遇到了要快速判断一个元素是否出现集合里的情况,就要考虑哈希表。

LeetCode 242.有效的字母异位词

题目规定了只出现26个小写字母,故用一个长度为26的数组替代HashMap,可以简化哈希表的遍历。

class Solution {
    public boolean isAnagram(String s, String t) {
        int[] record = new int[26];
        for(char c : s.toCharArray()){
            record[c - 'a'] += 1;
        }for(char c : t.toCharArray()){
            record[c - 'a'] -= 1;
        }
        for(int i : record){
            if(i != 0){
                return false;
            }
        }
        return true;
    }
}

LeetCode 349. 两个数组的交集

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        // HashSet自带去重特性
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();

        for(int i : nums1){
            set1.add(i);
        }

        for(int i : nums2){
            if(set1.contains(i)){
                set2.add(i);
            }
        }

        return set2.stream().mapToInt(x -> x).toArray();
    }
}

LeetCode 202. 快乐数

如果n不是快乐数,那么计算的过程会无限循环,用HashSet来快速判断是否存在这样的循环。

class Solution {
    public boolean isHappy(int n) {
        /** 如果n不是快乐数,那么计算的过程会无限循环,用HashSet来快速判断是否存在这样的循环 */
        Set<Integer> set = new HashSet<>();
        while(n != 1 && !set.contains(n)){
            set.add(n);
            n = getNext(n);
        }
        return n == 1;
    }

    private int getNext(int n){
        // 求数字n的每个位置上的数字的平方和
        int res = 0;
        while(n > 0){
            int tmp = n % 10;
            res += tmp * tmp;
            n /= 10;
        }
        return res;
    }
}

LeetCode 1. 两数之和

梦开始的地方。

最开始应该都是用双指针做的,那么这类题也可以用HashMap做,并且使用HashMap的话也可以将适用场景拓展到更多数之和。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>(); // <差值, 下标>
        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 new int[0];
    }
}