代码随想录Day6 | 242. 有效的字母异位值 、349. 两个数组的交集 、202. 快乐数、1.两数之和 | 哈希表

317 阅读2分钟

242. 有效的字母异位值

题目链接:242. 有效的字母异位词 - 力扣(LeetCode)

思路: 因为题目假设都是小写字母,可以使用大小为26的数组来当作哈希表,对第一个String的每一个char c,将索引c - 'a' ++,对第二个String的每一个char c,将索引c - 'a' --。之后遍历数组,发现不为0的值,返回false,否则返回true。

我的代码:

class Solution {
    public boolean isAnagram(String s, String t) {
        int[] s1 = encode(s);
        int[] s2 = encode(t);
        for (int i = 0; i < s1.length; i++) {
            if (s1[i] != s2[i])
                return false;
        }
        return true;
    }

    int[] encode(String s) {
        int[] count = new int[26];
        for (char c : s.toCharArray()) {
            int temp = c - 'a';
            count[temp]++;
        }
        return count;
    }
}

问题:

总结:

349. 两个数组的交集

题目链接:349. 两个数组的交集 - 力扣(LeetCode)

思路: 利用Set的特性:Set是一个不允许有重复元素的集合。

我的代码:

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet<>();
        Set<Integer> res = new HashSet<>();
        for (int i : nums1) {
            set.add(i);
        }
        for (int i : nums2) {
            if (set.contains(i)) 
                res.add(i);
        }
        return res.stream().mapToInt(x -> x).toArray();
    }
}

问题:

总结:

202. 快乐数

题目链接:202. 快乐数 - 力扣(LeetCode)

思路: 使用Set,将每次操作过的数存入Set,如果Set中出现过这个数字,说明陷入了循环,不可能是快乐数,返回false。循环的终止条件是n == 1.

我的代码:

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> set = new HashSet<>();
        while (n != 1) {
            if (set.contains(n)) return false;
            set.add(n);
            n = gerNext(n);
        }
        return true;
    }

    private int gerNext(int n) {
        int res = 0;
        while (n > 0) {
            int temp = n % 10;
            res += temp * temp;
            n = n / 10;
        }
        return res;
    }
}

问题:

总结:

1.两数之和

题目链接:1. 两数之和 - 力扣(LeetCode)

思路: 做了很多遍了,使用map,keyi的值,value为i的索引。遍历每一个数i,查找map中是否存在 = target与i的差的键,存在即返回两个值的索引。不存在即将这个i的值和索引存入map。

我的代码:

public int[] twoSum(int[] nums, int target) {
    int[] res = new int[2];
    if(nums == null || nums.length == 0){
        return res;
    }
    Map<Integer, Integer> map = new HashMap<>();
    for(int i = 0; i < nums.length; i++){
        int temp = target - nums[i];
        if(map.containsKey(temp)){
            res[1] = i;
            res[0] = map.get(temp);
        }
        map.put(nums[i], i);
    }
    return res;
}

总结:

今天复习了哈希表的相关概念和操作,对于变化有限的数值(如字母)可以使用int[]数组作为哈希表来存储。对于要求不重复的题目,可以使用Set。