面试算法题

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;
}
相关推荐
武汉格发Gofartlic1 小时前
如何跟踪FEMFAT许可使用情况
运维·python·算法·信息可视化·数据分析
m0_640743563 小时前
华为OD-2024年E卷-字符串分割[100分] -- python
数据结构·算法·华为od
剪一朵云爱着7 小时前
力扣面试题 17.05. 字母与数字
算法·leetcode
code喵喵8 小时前
八种数据结构简介
数据结构·算法·推荐算法
C语言小火车8 小时前
【C语言】银行账户管理系统丨源码+解析
c语言·c++·算法·课程设计
wen__xvn9 小时前
九日集训第三天
数据结构·算法·leetcode
dying_man9 小时前
LeetCode--33.搜索旋转排序数组
算法·leetcode
东方芷兰9 小时前
Leetcode 刷题记录 17 —— 堆
java·c++·b树·算法·leetcode·职场和发展
蒙奇D索大10 小时前
【数据结构】图论实战:DAG空间压缩术——42%存储优化实战解析
数据结构·笔记·学习·考研·图论·改行学it
Cyrus_柯10 小时前
C++(面向对象编程)
开发语言·c++·算法·面向对象