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;
    }
};
相关推荐
JuiceFS1 天前
从 MLPerf Storage v2.0 看 AI 训练中的存储性能与扩展能力
运维·后端
聚客AI1 天前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v1 天前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
CYRUS_STUDIO1 天前
用 Frida 控制 Android 线程:kill 命令、挂起与恢复全解析
android·linux·逆向
熊猫李1 天前
rootfs-根文件系统详解
linux
惯导马工1 天前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
chen9451 天前
mysql 3节点mgr集群部署
运维·后端
骑自行车的码农1 天前
【React用到的一些算法】游标和栈
算法·react.js
LH_R1 天前
OneTerm开源堡垒机实战(三):功能扩展与效率提升
运维·后端·安全
博笙困了1 天前
AcWing学习——双指针算法
c++·算法