【数据结构与算法】哈希表部分题目

两数之和

两数之和

还有一题:判断数组存在重复元素 太简单就不总结了。

最长和谐子序列

LeetCode:最长和谐子序列

题目描述:

和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。

现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。

示例:

输入: [1,3,2,2,5,2,3,7]
输出: 5
原因: 最长的和谐数组是:[3,2,2,2,3].

思想:

根据特性,最大最小相差1。可以想到,每次遍历temp时,取temp+1看是否存在,累加计数即可得到结果。注意 getOrDefault()、containsKey()、keySet()等方法的使用。

代码:

class Solution {
    public int findLHS(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int temp : nums){
            map.put(temp,map.getOrDefault(temp,0)+1);
        }
        int max = 0;
        for(int key : map.keySet()){
            if(map.containsKey(key+1)){
                max=Math.max(max,map.get(key+1)+map.get(key));
            }
        }
        return max;
    }
}

最长连续序列

LeetCode:最长连续序列

题目描述:

给定一个未排序的整数数组,找出最长连续序列的长度。

要求算法的时间复杂度为 O(n)。

示例:

输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。

思想:

这题需要套两层循环,但是时间复杂度却不是O(N^2)。外层循环遍历每一个 key ,针对当前key,遍历以key为开端的连续序列。例如 ABCD 连续。遍历到 A 时,遍历将 BCD 的数值累加到 A 上,并对 BCD 标记为-1,后续循环无需访问 BCD。最坏的情况,像54321时,每一个元素访问了两次,时间复杂度为O(2N)。

代码:

class Solution {
    public int longestConsecutive(int[] nums) {
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (int num : nums) {
            hashMap.put(num, 1);
        }
        int res = 0;
        for(int key : hashMap.keySet()){
            int val = hashMap.get(key);
            if(val==-1) continue;
            for(int i=key+1;hashMap.containsKey(i);++i){
                int v=hashMap.get(i);
                val+=v;
                hashMap.put(i,-1);
                if(v>1) break;
            }
            hashMap.put(key,val);
            res = Math.max(res,val);
        }
        return res;
    }
}
posted @ 2020-04-04 10:56  数小钱钱的种花兔  阅读(495)  评论(0编辑  收藏  举报