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;
    }
};
相关推荐
ajassi20003 小时前
开源 C++ QT Widget 开发(十五)多媒体--音频播放
linux·c++·qt·开源
焦耳加热3 小时前
阿德莱德大学Nat. Commun.:盐模板策略实现废弃塑料到单原子催化剂的高值转化,推动环境与能源催化应用
人工智能·算法·机器学习·能源·材料工程
wan5555cn3 小时前
多张图片生成视频模型技术深度解析
人工智能·笔记·深度学习·算法·音视频
JosieBook4 小时前
【远程运维】Linux 远程连接 Windows 好用的软件:MobaXterm 实战指南
linux·运维·windows
文档搬运工4 小时前
Linux MInt启动速度的优化
linux
u6064 小时前
常用排序算法核心知识点梳理
算法·排序
Broken Arrows4 小时前
Linux学习——管理网络安全(二十一)
linux·学习·web安全
Light605 小时前
领码方案|Linux 下 PLT → PDF 转换服务超级完整版:异步、权限、进度
linux·pdf·可观测性·异步队列·plt转pdf·权限治理·进度查询
羚羊角uou6 小时前
【Linux】命名管道
linux·运维·服务器
IT 小阿姨(数据库)6 小时前
PgSQL监控死元组和自动清理状态的SQL语句执行报错ERROR: division by zero原因分析和解决方法
linux·运维·数据库·sql·postgresql·centos