【长期更新】STL相关例题

LeetCode 128.最长连续序列

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> hash;
        for(const int& num : nums)
            hash.insert(num);//将nums中数遍历加入至哈希表中
        int ans = 0;
        while(!hash.empty()){
            int cur = *(hash.begin());
            hash.erase(cur);
            int next = cur + 1;
            int pre = cur - 1;
            while(hash.count(next))//当前数的右侧可连续,继续排除
                hash.erase(next++);
            while(hash.count(pre))//当前数的左侧可连续,继续排除
                hash.erase(pre--);
            ans = max(ans, next - pre - 1);//比较当前最大连续长度
        }
        return ans;
    }
};
  • set中存储的元素唯一,unordered下元素排列无序
  • set中Key即为Value值

LeetCode 1.两数之和

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int>hash;
        for(int i = 0;i < nums.size();i++){
            auto it = hash.find(target - nums[i]);//查 target - nums[i]的位置
            if(it != hash.end())//找到了具体的值
                return {it->second, i};//返回具体的key-value即满足要求的数对
            hash[nums[i]] = i;//没有找到,就记录下来
        }
        return {};
    }
};
  • unordered_map的end()迭代器指向最后一个元素之后的位置

LeetCode 1207. 独一无二的出现次数

class Solution {
public:
    bool uniqueOccurrences(vector<int>& arr) {
        unordered_map<int,int>dp;
        unordered_set<int>ans;
        for(int i = 0;i < arr.size();i++){
            dp[arr[i]]++;
        }
        for(const auto &i:dp){
            ans.insert(i.second);//second位置是出现次数
        }
        return dp.size() == ans.size();
    }
};

剑指 Offer 58 - I. 翻转单词顺序

class Solution {
public:
    string reverseWords(string s) {
        stack<string>st;
        string tem;
        int i = 0;
        while(i < s.size()){
            while(s[i] == ' ' && i < s.size())
                i++;
            tem.clear();
            if(i >= s.size())
                break;
            while(s[i] != ' ' && i < s.size()){
                tem += s[i];
                i++;
            }
            st.push(tem);
        }
        string ans;
        while(!st.empty()){
            ans += st.top();
            st.pop();
            if(!st.empty())
                ans += ' ';
        }
        return ans;
    }
};
  • 用栈存储每个单词
  • 取出一个完整的单词后,直接用空格连接str
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值