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;
    }
};
相关推荐
梨子串桃子_7 小时前
推荐系统学习笔记 | PyTorch学习笔记
pytorch·笔记·python·学习·算法
zfxwasaboy7 小时前
DRM KMS 子系统(4)Planes/Encoder/Connector
linux·c语言
夏鹏今天学习了吗7 小时前
【LeetCode热题100(83/100)】最长递增子序列
算法·leetcode·职场和发展
暮色_年华7 小时前
随想 2:对比 linux内核侵入式链表和 STL 非侵入链表
linux·c++·链表
情缘晓梦.7 小时前
C语言指针进阶
java·开发语言·算法
好学且牛逼的马7 小时前
【工具配置|docker】
运维·docker·容器
dnncool8 小时前
【Linux】操作系统发展
linux
文言一心8 小时前
LINUX离线升级 Python 至 3.11.9 操作手册
linux·运维·python
北邮刘老师8 小时前
智能体治理:人工智能时代信息化系统的全新挑战与课题
大数据·人工智能·算法·机器学习·智能体互联网