1. 程式人生 > 實用技巧 >資料結構之雜湊表

資料結構之雜湊表

有效的字母異位詞 題目 解析

對於特定的(數字小,範圍已知)可以用陣列代替雜湊

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

兩個數字的交集 題目 解析

數字太大就用Set

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new
HashSet<>(); Set<Integer> set2 = new HashSet<>(); for (int n: nums1) { set1.add(n); } for (int n: nums2) { if (set1.contains(n)) { set2.add(n); } } int[] ans = new int[set2.size()];
int index = 0; for (int n : set2) { ans[index++] = n; } return ans; } }

快樂數 題目 解析

快樂就完事了

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> sethappy = new HashSet<>();
        while (!sethappy.contains(n)) {
            if (n == 1) return true;
            sethappy.add(n);
            n = get(n);
        }
        return false;
    }
    public int get(int n) {
        int s = 0;
        while(n != 0) {
            s += (n%10)*(n%10);
            n = n/10;
        }
        return s;
    }
}

兩數之和 題目 解析

雙層迴圈748ms, 9ms 雜湊表2ms, 38.7ms

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