LeetCode Day06 349&202&1

74 阅读1分钟

今天刷题的内容主要是哈希表

349. 两个数组的交集

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        if(nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0){
            return null;
        }

        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);
            }
        }
        
        int[] res = new int[set2.size()];
        int index = 0;
        for(int i : set2){
            res[index ++] = i;
        }
        return res;
    }
}

202. 快乐数 这道题主要是要了解到一旦开始出现循环的数值我们就可以跳出反复求平方和这个loop去判断这个数字是不是快乐数了。

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

        return n == 1;
    }

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

1. 两数之和 leetcode第一题,梦开始的地方了。这道题的解法很多,但是再三提醒自己不要一拿到就开始暴力解题啦(算法白学qaq)利用hashmap的性质,key存储数组的值,value对应数组下标,可以很快给出题解。

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

        return res;
    }
}