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

54 阅读1分钟

今天是哈希表知识点的练习,主要是空间换时间的思想

242. 有效的字母异位词

用数组来模拟哈希表

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

349. 两个数组的交集

注意题目要求

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        //
        int[] hash = new int[1005];
        for(int i = 0; i < nums1.length; i++) {
            hash[nums1[i]] = 1;
        } 
        HashSet<Integer> set = new HashSet<>();
        for(int i = 0; i < nums2.length; i++) {
            if(hash[nums2[i]] == 1) {
                set.add(nums2[i]);
            }
        }
        int[] result = new int[set.size()];
        int index = 0;
        for(int ele : set) {
            result[index++] = ele;
        }
        return result;
    }
}

202. 快乐数

思路类似上一道题,也是用一个set,然后判断是否发生了循环

class Solution {
    public boolean isHappy(int n) {
        HashSet<Integer> set = new HashSet<>();
        while(n != 1 && !set.contains(n)) {
            set.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 /= 10;
        }
        return res;
    }
}

1. 两数之和

做了无数遍的题,map经典题

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(target - nums[i])) {
                return new int[]{i, map.get(target - nums[i])};
            }
            map.put(nums[i], i);
        }
        return new int[2];
    }
}