面试算法题

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;
}
相关推荐
在未来等你4 分钟前
Elasticsearch面试精讲 Day 13:索引生命周期管理ILM
大数据·分布式·elasticsearch·搜索引擎·面试
奔跑吧 android2 小时前
【linux kernel 常用数据结构和设计模式】【数据结构 2】【通过一个案例属性list、hlist、rbtree、xarray数据结构使用】
linux·数据结构·list·kernel·rbtree·hlist·xarray
汉克老师2 小时前
第十四届蓝桥杯青少组C++选拔赛[2023.2.12]第二部分编程题(5、机甲战士)
c++·算法·蓝桥杯·01背包·蓝桥杯c++·c++蓝桥杯
Mr_Xuhhh3 小时前
项目需求分析(2)
c++·算法·leetcode·log4j
默默无名的大学生4 小时前
数据结构—顺序表
数据结构·windows
c++bug4 小时前
六级第一关——下楼梯
算法
PAK向日葵4 小时前
【C/C++】面试官:手写一个memmove,要求性能尽可能高
c语言·c++·面试
Morri34 小时前
[Java恶补day53] 45. 跳跃游戏Ⅱ
java·算法·leetcode
林木辛4 小时前
LeetCode热题 15.三数之和(双指针)
算法·leetcode·双指针
AndrewHZ4 小时前
【3D算法技术】blender中,在曲面上如何进行贴图?
算法·3d·blender·贴图·三维建模·三维重建·pcg