面试算法题

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;
}
相关推荐
闪电麦坤958 分钟前
数据结构:数组:合并数组(Merging Arrays)
数据结构·算法
3Katrina9 分钟前
前端面试之防抖节流(一)
前端·javascript·面试
kk_stoper9 分钟前
使用Ruby接入实时行情API教程
java·开发语言·javascript·数据结构·后端·python·ruby
myloveasuka25 分钟前
leetcode11.盛最多水的容器
c语言·数据结构·c++·leetcode
C++ 老炮儿的技术栈36 分钟前
tinyxml2 开源库与 VS2010 结合使用
c语言·数据结构·c++·算法·机器人
平平无奇我要摘星星42 分钟前
leetcode1_455.分发饼干
算法·leetcode
Joern-Lee1 小时前
机器学习算法:支持向量机SVM
算法·机器学习·支持向量机
秋说1 小时前
【PTA数据结构 | C语言版】计算1~n与1~m每一项相互乘积的和
c语言·数据结构·算法
秋说1 小时前
【PTA数据结构 | C语言版】计算1~n平方的和加上1~n的和
c语言·数据结构·算法
C++ 老炮儿的技术栈1 小时前
Visual Studio 2022 MFC Dialog 添加Toolbar及Tips提示
服务器·c语言·数据库·c++·ide·算法·visual studio