数据结构之哈希表

有效的字母异位词 题目 解析

对于特定的(数字小,范围已知)可以用数组代替哈希

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];
    }
}

 

最长连续序列 题目 解析

hashset去重真的方便

class Solution {
    public int longestConsecutive(int[] nums) {
        Arrays.sort(nums);
        int count = 0;
        Set<Integer> hashset = new HashSet<>();
        for (int n: nums) {
            hashset.add(n);
        }
        for (int n : nums) {
            if (!hashset.contains(n-1)) {
                int cur = 0;
                while (hashset.contains(n++)) {
                    cur++;
                }
                count = Math.max(cur, count);
            }
        }
        return count;
    }
}

 

posted @ 2020-11-05 21:42  CPJ31415  阅读(72)  评论(0)    收藏  举报