当前位置:   article > 正文

算法面试题目1

算法面试题目1

自从July来我们演讲之后,最后也一直在看他的博客。话说很久没有A题了,状态大不如前,最近在正在翻阅一些算法的资料,着手准备在这学期课少的情况下,再次开启刷题模式。今天上政治的时候用手机看CSDN的时候,看到了这样一道算法面试题目。 题目要求为在O(1)的实现的push_stack, pop_stack, get_min_val, get_max_val的操作,YY了一下,中午吃饭的时候把代码写了,发一贴,算是正式刷题之前的一些预备工作吧。

  1. #include <cstdio>
  2. #include <cmath>
  3. #include <cstdlib>
  4. #include <cstring>
  5. #include <ctime>
  6. using namespace std;
  7. const int MAX_INTEGER = 0x3f3f3f3f;
  8. const int MAX_STACKSIZE = 100000 + 10;
  9. void init_seed() {
  10. srand((unsigned)(time(NULL)));
  11. return ;
  12. }
  13. int get_random() {
  14. return rand() % MAX_INTEGER;
  15. }
  16. int src_stack[MAX_STACKSIZE], maxVal[MAX_STACKSIZE], minVal[MAX_STACKSIZE];
  17. int min_Val, max_Val, src_index, min_index, max_index;
  18. void init_stack() {
  19. src_index = max_index = min_index = 0;
  20. min_Val = MAX_INTEGER; max_Val = -MAX_INTEGER;
  21. }
  22. void push_stack(int val) {
  23. src_stack[src_index++] = val;
  24. if(min_Val > val) {
  25. min_Val = val;
  26. }
  27. minVal[min_index++] = min_Val;
  28. if(max_Val < val) {
  29. max_Val = val;
  30. }
  31. maxVal[max_index++] = max_Val;
  32. return ;
  33. }
  34. void pop_stack() {
  35. if(src_index <= 0) {
  36. printf("The stack is empty!\n");
  37. return ;
  38. }
  39. src_index--, max_index--, min_index--;
  40. return ;
  41. }
  42. int get_min_val() {
  43. if(min_index <= 0) return -1;
  44. return minVal[min_index-1];
  45. }
  46. int get_max_val() {
  47. if(max_index <= 0) return -1;
  48. return maxVal[max_index-1];
  49. }
  50. int main() {
  51. #ifdef sponge_wxy
  52. freopen("aa.in", "r", stdin);
  53. freopen("bb.out", "w", stdout);
  54. #endif
  55. init_seed();
  56. init_stack();
  57. push_stack(1);
  58. printf("The max value is : %d\n", get_max_val());
  59. printf("THe min val is: %d\n", get_min_val());
  60. push_stack(2);
  61. printf("The max value is : %d\n", get_max_val());
  62. printf("THe min val is: %d\n", get_min_val());
  63. push_stack(2);
  64. printf("The max value is : %d\n", get_max_val());
  65. printf("THe min val is: %d\n", get_min_val());
  66. push_stack(3);
  67. printf("The max value is : %d\n", get_max_val());
  68. printf("THe min val is: %d\n", get_min_val());
  69. pop_stack();
  70. printf("The max value is : %d\n", get_max_val());
  71. printf("THe min val is: %d\n", get_min_val());
  72. pop_stack();
  73. printf("The max value is : %d\n", get_max_val());
  74. printf("THe min val is: %d\n", get_min_val());
  75. pop_stack(); pop_stack();
  76. printf("The max value is : %d\n", get_max_val());
  77. printf("THe min val is: %d\n", get_min_val());
  78. return 0;
  79. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/神奇cpp/article/detail/856550
推荐阅读
相关标签
  

闽ICP备14008679号