2024-09-27

  1. 239. 滑动窗口最大值 - 力扣(LeetCode)
class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        vector<int> ans;
        for (int i = 0; i < nums.size(); i++) {
            while (!q.empty() && q.front() <= i - k) 
                q.pop_front();
            while (!q.empty() && nums[q.back()] <= nums[i])
                q.pop_back();
            q.push_back(i);
            if (i >= k - 1)
            ans.push_back(nums[q.front()]);
        }
        return ans;
    }

private:
    deque<int> q;
};
  1. 1. 两数之和 - 力扣(LeetCode)
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        for (int i = 0; i < nums.size(); i++) {
            if (h.find(target - nums[i]) != h.end())
                return {h[target - nums[i]], i};
            h[nums[i]] = i;
        }
        return {};
    }

private:
    // <值, 下标>
    unordered_map<int, int> h;
};
  1. 874. 模拟行走机器人 - 力扣(LeetCode)
class Solution {
public:
    int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
        unordered_set<long long> obs;
        for (const vector<int>& obstacle : obstacles) {
            obs.insert(calc(obstacle));
        }
        int x = 0, y = 0;
        int dir = 0;
        int ans = 0;
        for (int& command : commands) {
            if (command == -2)
                dir = (dir + 3) % 4;
            else if (command == -1)
                dir = (dir + 1) % 4;
            else {
                for (int i = 0; i < command; i++) {
                    int nx = x + dx[dir];
                    int ny = y + dy[dir];
                    if (obs.find(calc({nx, ny})) != obs.end()) break;
                    x = nx;
                    y = ny;
                }
            }
            ans = max(ans, x * x + y * y);
        }
        return ans;
    }

private:
    long long calc(const vector<int>& obstacle) {
        return (obstacle[0] + 3e4) * (6e4 + 1) + obstacle[1] + 3e4;
    }

    const int dx[4] = {0, 1, 0, -1};
    const int dy[4] = {1, 0, -1, 0};
};
  1. 49. 字母异位词分组 - 力扣(LeetCode)
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        for (string& str : strs) {
            string copy = str;
            sort(copy.begin(), copy.end());
            groups[copy].push_back(str);
        }
        vector<vector<string>> ans;
        for (const pair<string, vector<string>>& group : groups) {
            ans.push_back(group.second);
        }
        return ans;
    }
private:
    unordered_map<string, vector<string>> groups;
};
  1. 30. 串联所有单词的子串 - 力扣(LeetCode)
    O(MN*ls)
class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        int tot = 0;
        for (string& word : words) {
            tot += word.length();
            wordMap[word]++;
        }
        vector<int> ans;
        k = words[0].length();
        for (int i = 0; i + tot <= s.length(); i++) {
            if (isValid(s.substr(i, tot))) 
                ans.push_back(i);
        }
        return ans;
    }

private:
    unordered_map<string, int> wordMap;
    int k;

    bool isValid(const string& str) {
        unordered_map<string, int> splitMap;
        for (int i = 0; i + k <= str.length(); i+= k) {
            splitMap[str.substr(i, k)]++;
        }
        return equalsMap(wordMap, splitMap);
    }

    bool equalsMap(unordered_map<string, int>& a, unordered_map<string, int>& b) {
        for (auto& kv : a) {
            const string& key = kv.first;
            int val = kv.second;
            if (b.find(key) == b.end() || b[key] != val) 
                return false;
        }
        for (auto& kv : b) {
            const string& key = kv.first;
            int val = kv.second;
            if (a.find(key) == a.end() || a[key] != val) 
                return false;
        }
        return true;
    }
};

O(N*ls)

class Solution {
public:
    vector<int> findSubstring(string &s, vector<string> &words) {
        // 存储结果的数组
        vector<int> res;  
        // 单词数量、单词长度、字符串 s 的长度
        int m = words.size(), n = words[0].size(), ls = s.size();  
        // 外层循环,从每个可能的起始位置 i 开始
        for (int i = 0; i < n && i + m * n <= ls; ++i) {  
            // 用于统计当前窗口内单词的出现次数 与 words 中的差异
            unordered_map<string, int> differ;  
            // 统计从当前起始位置 i 开始的 m 个单词
            for (int j = 0; j < m; ++j) 
                // 将子串加入到 differ 中并计数
                ++differ[s.substr(i + j * n, n)];  
            // 遍历 words 中的每个单词,从 differ 中减去
            for (string &word: words) 
                // 此处如若differ中不存在word,则插入时其值为负数
                // 如果单词的计数减为 0,则从 differ 中删除
                if (--differ[word] == 0) 
                    differ.erase(word);
            // 内层循环,从起始位置 i 开始滑动窗口
            for (int start = i; start < ls - m * n + 1; start += n) {
                if (start != i) {
                    // 添加新进入窗口的单词到 differ 中
                    string newWord = s.substr(start + (m - 1) * n, n);
                    // 由于differ的值中存在负数,所以++后会出现0
                    if (++differ[newWord] == 0) 
                        differ.erase(newWord);
                    // 移除窗口左侧移出的单词
                    string oldWord = s.substr(start - n, n);
                    if (--differ[oldWord] == 0) 
                        differ.erase(oldWord);
                }
                // 如果 differ 为空,表示当前窗口符合要求,将起始位置加入结果数组 res
                if (differ.empty()) 
                    res.push_back(start);
            }
        }
        return res;
    }
};
  1. 146. LRU 缓存 - 力扣(LeetCode)
class LRUCache {
public:
    LRUCache(int capacity) {
        this->capacity = capacity;
        head = new Node();
        tail = new Node();
        head->next = tail;
        tail->pre = head;
    }
    
    int get(int key) {
        if (map.find(key) == map.end()) return -1;
        Node* node = map[key];
        remove(node);
        insert(node);
        return node->value;
    }
    
    void put(int key, int value) {
        if (map.find(key) == map.end()) {
            Node* node = new Node();
            node->key = key;
            node->value = value;
            map[key] = node;
            insert(node);
            if (map.size() > capacity) {
                Node* node = tail->pre;
                map.erase(node->key);
                remove(node);
            }
        }
        else {
            Node* node = map[key];
            remove(node);
            insert(node);
            node->value = value;
        }
    }

private:
    struct Node {
        int key;
        int value;
        Node* pre;
        Node* next;
    };
    Node* head;
    Node* tail;
    int capacity;
    unordered_map<int, Node*> map;

    void remove(Node* node) {
        node->pre->next = node->next;
        node->next->pre = node->pre;
    }
    void insert(Node* node) {
        node->next = head->next; head->next->pre = node;
        head->next = node; node->pre = head;
    }
};


/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 1.头部删除
 2.随机访问每个元素
 3.中间删除
 */
  1. 1248. 统计「优美子数组」 - 力扣(LeetCode)
class Solution {
public:
    int numberOfSubarrays(vector<int>& nums, int k) {
        // 原问题:子段的奇数数量
        // 新问题:奇数看作0,偶数看作1,统计子段和为k的子段数量
        // 即 s[r] - s[l-1] == k
        // 两数之差问题
        int n = nums.size();
        vector<int> preSum(n + 1);
        preSum[0] = 0;
        for (int i = 1; i <= n; i++)
            preSum[i] = preSum[i - 1] + nums[i - 1] % 2;
        vector<int> count(n + 1);
        count[preSum[0]]++;
        int ans = 0;
        for (int i = 1; i <= n; i++) {
            if (preSum[i] - k >= 0) 
                ans += count[preSum[i] - k];
            count[preSum[i]]++;
        }
        return ans;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,084评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,623评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,450评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,322评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,370评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,274评论 1 300
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,126评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,980评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,414评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,599评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,773评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,470评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,080评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,713评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,852评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,865评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,689评论 2 354

推荐阅读更多精彩内容