48.日常算法

1.面试题 03.06. 动物收容所

题目来源

动物收容所。有家动物收容所只收容狗与猫,且严格遵守"先进先出"的原则。在收养该收容所的动物时,收养人只能收养所有动物中"最老"(由其进入收容所的时间长短而定)的动物,或者可以挑选猫或狗(同时必须收养此类动物中"最老"的)。换言之,收养人不能自由挑选想收养的对象。请创建适用于这个系统的数据结构,实现各种操作方法,比如enqueue、dequeueAny、dequeueDog和dequeueCat。允许使用Java内置的LinkedList数据结构。enqueue方法有一个animal参数,animal[0]代表动物编号,animal[1]代表动物种类,其中 0 代表猫,1 代表狗。dequeue*方法返回一个列表[动物编号, 动物种类],若没有可以收养的动物,则返回[-1,-1]。

示例 1:

输入:

"AnimalShelf", "enqueue", "enqueue", "dequeueCat", "dequeueDog", "dequeueAny"

\[\], \[\[0, 0\]\], \[\[1, 0\]\], \[\], \[\], \[\]

输出:

null,null,null,\[0,0\],\[-1,-1\],\[1,0\]

c 复制代码
class AnimalShelf {
    queue<int> cats, dogs;
public:
    AnimalShelf() {
    }

    void enqueue(vector<int> animal) {
        int id = animal[0], type = animal[1];
        if (type) dogs.push(id);
        else cats.push(id);
    }
    
    vector<int> dequeueAny() {
        if (cats.empty()) return dequeueDog();
        else if (dogs.empty()) return dequeueCat();
        if (cats.front() < dogs.front()) return dequeueCat();
        return dequeueDog();
    }
    
    vector<int> dequeueDog() {
        if(dogs.empty()) return {-1, -1};
        int id = dogs.front();
        dogs.pop();
        return {id, 1};
    }
    
    vector<int> dequeueCat() {
        if(cats.empty()) return {-1, -1}; 
        int id = cats.front();
        cats.pop();
        return {id, 0};
    }
};

1.字母异位词分组

题目来源

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。字母异位词 是由重新排列源单词的所有字母得到的一个新单词。

示例 1:

输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]

输出: [["bat"],["nat","tan"],["ate","eat","tea"]]

示例 2:

输入: strs = [""]

输出: [[""]]

c 复制代码
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> hash;
        for (auto & s : strs){
            string temp = s;
            sort(temp.begin(), temp.end());
            hash[temp].push_back(s);
        }
        vector<vector<string>> ret;
        for (auto & [x, y] : hash){
            ret.push_back(y);
        }
        return ret;
    }
};
相关推荐
序属秋秋秋27 分钟前
《Linux系统编程之入门基础》【Linux基础 理论+命令】(上)
linux·运维·服务器·ubuntu·centos·命令模式
知白守黑2672 小时前
docker资源限制
运维·docker·容器
霍格沃兹测试开发学社测试人社区2 小时前
新手指南:通过 Playwright MCP Server 为 AI Agent 实现浏览器自动化能力
运维·人工智能·自动化
ximy13353 小时前
AI服务器工作之服务器的种类分类
运维·服务器
恒创科技HK3 小时前
香港服务器CPU中E5和Gold的区别
运维·服务器
Han.miracle3 小时前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode
一张假钞5 小时前
Ubuntu SSH 免密码登陆
linux·ubuntu·ssh
mit6.8245 小时前
前后缀分解
算法
Wang's Blog6 小时前
Linux小课堂: 文件操作警惕高危删除命令与深入文件链接机制
linux·运维·服务器
你好,我叫C小白6 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while