面试算法题

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;
}
相关推荐
iAkuya9 分钟前
(leetcode)力扣100 26环状链表2(双指针)
算法·leetcode·链表
sin_hielo10 分钟前
leetcode 2402(双堆模拟,小根堆)
数据结构·算法·leetcode
37手游后端团队14 分钟前
Cursor 工作区使用技巧:让 AI 真正理解你的多项目协作
后端·面试·架构
weixin_4617694019 分钟前
3. 无重复字符的最长子串
c++·算法·滑动窗口·最长字串
Morwit21 分钟前
【力扣hot100】 312. 戳气球(区间dp)
c++·算法·leetcode
李拾叁的摸鱼日常27 分钟前
Java Optional 最佳实践+注意事项+避坑指南
java·后端·面试
CoovallyAIHub30 分钟前
摄像头如何“看懂”你的手势?手势识别实现新人机交互
深度学习·算法·计算机视觉
over69736 分钟前
用 React Context 实现全局主题切换:从零搭建暗黑/亮色模式系统
前端·react.js·面试
妮妮喔妮40 分钟前
前端字节面试大纲
前端·面试·职场和发展
Q741_14742 分钟前
C++ 栈 模拟 力扣 394. 字符串解码 每日一题 题解
c++·算法·leetcode·模拟·