LeetCode——哈希表

LeetCode——哈希表

1、数组中两个数的和为给定值
T1 Two Sum (Easy)
LeetCode——哈希表_第1张图片

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> m;
        vector<int> res;
        for(int i=0; i<nums.size(); ++i){
            m[nums[i]] = i;
        }
        for(int i=0; i<nums.size(); ++i){
            int t=target-nums[i];
            if(m.count(t) && m[t]!=i){
                res.push_back(i);
                res.push_back(m[t]);
                break;
            }
        }
        return res;
    }
};

2、判断数组是否含有重复元素
T217 Contains Duplicate (Easy)
LeetCode——哈希表_第2张图片

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_map<int, int> m;
        for(int i=0; i<nums.size(); ++i){
            if(m.find(nums[i]) != m.end())  return true;
            ++m[nums[i]];
        }
        return false;

    }
};

3、最长和谐序列
T594 Longest Harmonious Subsequence (Easy)
LeetCode——哈希表_第3张图片

class Solution {
public:
    int findLHS(vector<int>& nums) {
        map<int, int> m;
        int res=0;
        for(int num:nums) ++m[num];
        for(auto a:m){
            if(m.count(a.first+1)){
                res=max(res, m[a.first]+m[a.first+1]);
            }
        }
        return res;

    }
};

4、最长连续序列
T128 Longest Consecutive Sequence (Hard)
LeetCode——哈希表_第4张图片

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_map<int, int> m;
        for(int num : nums){
            if(m.count(num))  continue;

            auto left = m.find(num-1);
            auto right = m.find(num+1);
            int l = left!=m.end() ? left->second : 0;
            int r = right!=m.end() ? right->second : 0;
            if(l>0 && r>0)
            m[num] = m[num-l] = m[num+r] =l+r+1;
            else if(l>0)
            m[num] =m[num-l] =l+1;
            else if(r>0)
            m[num] = m[num+r] = r+1;
            else
            m[num] = 1;
        }
        int ans = 0;
        for(const auto& kv : m)
        ans = max(ans, kv.second);
        return ans;

    }
};

你可能感兴趣的:(leetcode刷题,leetcode,哈希表)