面试算法题

1

使用栈实现队列

cpp 复制代码
#include <iostream>
#include <stack>
class MyQueue
{
public:
    MyQueue() {}

    void push(int x)
    {
        in.push(x); // 直接将元素push入in栈
    }

    int pop()
    {
        int data = peek(); // 先查一遍,就是更新一遍out栈
        out.pop();
        return data;
    }
    // 查找队列头的元素
    int peek()
    {
        // 首先检查out栈是否为空,如果为空,则将in栈的元素出栈然后入栈out
        if (out.empty())
            // 这里刚开始写成当in为空时执行循环了,就会出错
            while (!in.empty()) // 必须全部将in栈的数据搬到out栈,不然会导致数据混乱
            {
                out.push(in.top());
                in.pop();
            }
        return out.top();
    }

    bool empty()
    {
        return in.empty() && out.empty();
    }

private:
    std::stack<int> in;
    std::stack<int> out;
};

int main()
{
    MyQueue que;
    que.push(1);
    que.push(2);
    que.push(3);
    que.push(4);
    que.push(2);

    std::cout << que.pop() << std::endl;
    std::cout << que.pop() << std::endl;
    std::cout << que.pop() << std::endl;
    std::cout << que.pop() << std::endl;
    std::cout << que.pop() << std::endl;
    return 0;
}

2

输入一个数组,找到任意一个峰值元素返回其位置,时间复杂度为O(logN)。

cpp 复制代码
#include <iostream>
#include <vector>
/* 输入一个数组,找到任意一个峰值元素(大于其最近左边和右边的元素),返回其位置,时间复杂度是O(logN) */

int peak_Index(std::vector<int> &data)
{
    int left = 0;
    int right = data.size() - 1;
    while (left < right)
    {
        int mid = left + (right - left) / 2;
        if (data[mid] > data[mid + 1]) // 比右边的数大,那就在mid左边
            right = mid;               // mid有可能是峰值元素
        else                           // 比右边数小,那就在mid右边
            left = mid + 1;            // mid不可能是峰值元素
    }
    return left;
}

int main()
{
    std::vector<int> data = {1, 2, 3, 1};
    std::cout << peak_Index(data) << std::endl;
    return 0;
}
相关推荐
江畔柳前堤16 小时前
大语言模型分布式训练:从并行策略到万卡工程的系统梳理
人工智能·分布式·深度学习·算法·目标检测·机器学习·语言模型
Doraemomo16 小时前
数据结构-环形链表
java·数据结构·链表
Forever Nore17 小时前
LeetCode 4 寻找两个正序数组的中位数 - 二分
算法·leetcode
罗西的思考19 小时前
【OpenClaw具身硬件】MiniClaw 阅读笔记---(1)基础
人工智能·算法·机器学习
蛋先生DX19 小时前
大模型参数存储格式揭秘:BF不是男朋友
深度学习·算法·llm
爱跳舞的烤冷面20 小时前
自学嵌入式第22天(数据结构——哈希)
数据结构·算法·哈希算法
猎嘤一号20 小时前
博弈论(Game Theory)的理论、算法与工程
人工智能·算法·安全·博弈论
月光船幽幽20 小时前
影子模式下保护 logits 不被修改
人工智能·python·算法
马拉AI20 小时前
腾讯开源 Agent 记忆系统,AI“换对话就忘”的问题有了新解法(附安装使用教程)
人工智能·算法·开源·科研
用户9385156350721 小时前
Type vs Interface:读完这篇就没有面试官能难倒你了
前端·面试·typescript