day6 哈希表part01: 242.有效的字母异位词|349. 两个数组的交集|202. 快乐数|1. 两数之和

242.有效的字母异位词 

class Solution {
    public boolean isAnagram(String s, String t) {
       int[] record = new int[26];
       //a = 97. so a - a = 0, b - a = 1. 直接使用减法,不用记acii码值。
       //遍历第一个string++, 遍历第二个string--.数组里的数字都是0,就是一样的。
       for(int i = 0; i < s.length(); i++){
        record[s.charAt(i) - 'a']++;
       } 
       for(int i = 0; i < t.length(); i++){
        record[t.charAt(i) - 'a']--;
       }
       for(int i : record){
        if(i != 0){
            return false;
        }
       }

       return true;
    }
}

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 去重,遍历第一个存入,第二个只对比,有的话就放在一个新的set里边
        //把set里边的转换成数组
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> result = new HashSet<>();
        for(int i : nums1){
            set1.add(i);
        }
        for(int i : nums2){
            if(set1.contains(i)){
                result.add(i);
            }
        }
        int[] arr = new int[result.size()];
        int k = 0;
        for(int i : result){
            arr[k] = i;
            k++;
        }
        return arr;
    }
}

202. 快乐数

class Solution {
    public boolean isHappy(int n) {
        //放在set里,如果set里有了就是循环了,不是快乐数
        //set里有1就是快乐数,注意数学基本运算的写法
        Set<Integer> res = new HashSet<>();
        while (n != 1 && !res.contains(n)){
            res.add(n);
            n = square(n);
        }
        return n == 1;
    }
    public int square (int n){
        int sum = 0;
        while(n > 0){
            int temp = n % 10;
            sum += temp * temp;
            n = n/10;
        }
        return sum;
    }
}

 

1. 两数之和

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];

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

 

posted @ 2024-08-20 17:33  爱刷题的小盒子  阅读(257)  评论(0编辑  收藏  举报