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;
    }
};
相关推荐
ALex_zry1 小时前
Docker Compose运维技术实战分享:从安装到架构解析
运维·docker·架构
轻抚酸~3 小时前
KNN(K近邻算法)-python实现
python·算法·近邻算法
t198751285 小时前
在Ubuntu 22.04系统上安装libimobiledevice
linux·运维·ubuntu
skywalk81635 小时前
linux安装Code Server 以便Comate IDE和CodeBuddy等都可以远程连上来
linux·运维·服务器·vscode·comate
Yue丶越5 小时前
【C语言】字符函数和字符串函数
c语言·开发语言·算法
@游子6 小时前
内网渗透笔记-Day5
运维·服务器
晚风吹人醒.6 小时前
缓存中间件Redis安装及功能演示、企业案例
linux·数据库·redis·ubuntu·缓存·中间件
小白程序员成长日记6 小时前
2025.11.24 力扣每日一题
算法·leetcode·职场和发展
有一个好名字6 小时前
LeetCode跳跃游戏:思路与题解全解析
算法·leetcode·游戏
记得记得就1516 小时前
【Nginx 性能优化与防盗链】
运维·nginx·性能优化