LeetCode 哈希表

基础部分

1. 两数之和

简单

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++){
            if (map.containsKey(target-nums[i])){
                return new int[]{map.get(target-nums[i]), i};
            }else {
                map.put(nums[i], i);
            }
        }
        return new int[]{};
    }
}

217. 存在重复元素

难度简单275

给定一个整数数组,判断是否存在重复元素。

如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false

示例 1:

输入: [1,2,3,1]
输出: true

示例 2:

输入: [1,2,3,4]
输出: false

示例 3:

输入: [1,1,1,3,3,4,3,2,4,2]
输出: true
class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums){
            if (set.contains(num)) return true;
            set.add(num);
        }
        return false;
    }
}

594. 最长和谐子序列

简单

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

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

示例 1:

输入: [1,3,2,2,5,2,3,7]
输出: 5
原因: 最长的和谐数组是:[3,2,2,2,3].
class Solution {
    public int findLHS(int[] nums) {
        Map<Integer,Integer> map = new TreeMap<>();
        for (int num : nums)
            map.put(num, map.getOrDefault(num,0)+1);
        List<Integer> list = new ArrayList<>();
        for (int key : map.keySet()) list.add(key);
        int res = 0;
        for (int i = 1; i < list.size(); i++){
            res = Math.max(res,list.get(i)-list.get(i-1)==1 ? map.get(list.get(i)) + map.get(list.get(i-1)) : 0);
        }
        return res;
    }
}

128. 最长连续序列

困难

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

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

示例:

输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) set.add(num);
        int res = 0;
        for (Integer num : set){
            if (set.contains(num+1)) continue;
            int number = num - 1, len = 1;
            while (set.contains(number)){
                len++;
                number--;
            }
            res = Math.max(res, len);
        }
        return res;
    }
}

频率排序

711,1044,3,726,85,149,535,974,718,381,37,159,336,648,692,594,325,939,76,204,694

原文地址:https://www.cnblogs.com/peng8098/p/leetcode12.html