其他分享
首页 > 其他分享> > 力扣202题(哈希表)

力扣202题(哈希表)

作者:互联网

202、快乐数

基本思想:

题目是中说如果平方和变不到1的话可能会无限循环

说明求和过程中,和 会重复出现

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

具体实现:

只要record重复出现一次就退出循环,得出不是快乐数的结论

要会分解一个数

代码:

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> record = new HashSet<>();
        while (n != 1 && !record.contains(n)) {
            record.add(n);
            n = getNextNumber(n);
        }
        return n == 1;
    }

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

 349、两个数组的交集

基本思想:

输出每一个元素一定是唯一的,也就是说输出的结果去重,可以不考虑输出结果的顺序

所以要使用哈希表

具体实现:

使用了数组,因为数值大小有限制

如果没有限制数值的大小,就无法使用数组

如果哈希值比较少,特别分散,跨度非常大,使用数组就造成空间的极大浪费

代码:

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> set1 = new HashSet<>();
        Set<Integer> resSet = new HashSet<>();
        for (int i : nums1){
            set1.add(i);
        }
        for (int i : nums2){
            if (set1.contains(i)){
                resSet.add(i);
            }
        }
        int[] resArr = new int[resSet.size()];
        int index = 0;
        for (int i : resSet){
            resArr[index++] = i;
        }
        return resArr;
    }
}

 

标签:202,return,int,力扣,resSet,哈希,new,nums2
来源: https://www.cnblogs.com/zhaojiayu/p/15483634.html