鱼C论坛

 找回密码
 立即注册
查看: 2001|回复: 2

[技术交流] C++刷面试题(比大小)【堆】【美团】【2020】

[复制链接]
发表于 2020-5-23 17:27:36 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
题目描述:
  1. 给定一个整数数组,返回一个数组。该返回数组中第i个数字为,原数组中第i个位置的数字至少往右走多少步才能遇到比它大的数字。如果遇不到或者已经处于最右的位置,则置为-1。


  2. 输入描述:
  3. 输入为多行,第一行为一个整数N,1≤N≤106

  4. 接下来一共有N行,每一行为一个整数M,0≤M≤232-1



  5. 输出描述:
  6. 输出 N 行,每行一个数字表示转换之后的数组

  7. 示例1
  8. 输入
  9. 5
  10. 91
  11. 10
  12. 3
  13. 22
  14. 40
  15. 输出
  16. -1
  17. 2
  18. 1
  19. 1
  20. -1
复制代码

  1. #include <vector>
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <stack>

  5. using namespace std;

  6. vector<int> solution(vector<int> &input){
  7.     vector<int> res(input.size(), 0);
  8.     int temp = input.size()-1;
  9.     stack<int> store;
  10.     for(int i = temp; i >= 0; i--){
  11.         while(!store.empty() && input[i] >= input[store.top()]){
  12.             store.pop();
  13.         }
  14.         if(store.empty()) res[i] = -1;
  15.         else res[i] = store.top()-i;
  16.         store.push(i);
  17.     }
  18.     return res;
  19. }

  20. int main(void){
  21.     int total;
  22.     cin >> total;
  23.     int number;
  24.     vector<int> input;
  25.     for(int i = 0; i < total; i++){
  26.         cin >> number;
  27.         input.push_back(number);
  28.     }
  29.     vector<int> res = solution(input);
  30.     for(auto cha : res) cout << cha << endl;
  31.     return 0;
  32. }
复制代码


注意事项:
1.用以维持一个从堆的底部到头部依次递减的序列。
2.类比:https://fishc.com.cn/thread-169443-1-1.html 反向循环

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-5-23 17:28:16 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-6-2 16:59:12 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-20 07:42

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表