LeetCode題解——哈希表

哈希表

兩數之和

給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。

你可以假設每種輸入只會對應一個答案。但是,數組中同一個元素不能使用兩遍。

示例:

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

因爲 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

HashMap解法

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

存在重複元素

給定一個整數數組,判斷是否存在重複元素。

如果任意一值在數組中出現至少兩次,函數返回 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) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            if (map.containsKey(num)) {
                return true;
            } else {
                map.put(num, 1);
            }
        }
        return false;
    }
}

最長和諧子序列

和諧數組是指一個數組裏元素的最大值和最小值之間的差別正好是1。

現在,給定一個整數數組,你需要在所有可能的子序列中找到最長的和諧子序列的長度。

示例 1:

輸入: [1,3,2,2,5,2,3,7]
輸出: 5
原因: 最長的和諧數組是:[3,2,2,2,3].
說明: 輸入的數組長度最大不超過20,000.

解法

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

最長連續序列

給定一個未排序的整數數組,找出最長連續序列的長度。

要求算法的時間複雜度爲 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 (int num : nums) {
            if (!set.contains(num - 1)) {
                int currentNum = num;
                int currentStreak = 1;
                while (set.contains(currentNum + 1)) {
                    currentNum++;
                    currentStreak++;
                }
                res = Math.max(currentStreak, res);
            }
        }
        return res;
    }
}

推薦閱讀


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章