赞
踩
自从July来我们演讲之后,最后也一直在看他的博客。话说很久没有A题了,状态大不如前,最近在正在翻阅一些算法的资料,着手准备在这学期课少的情况下,再次开启刷题模式。今天上政治的时候用手机看CSDN的时候,看到了这样一道算法面试题目。 题目要求为在O(1)的实现的push_stack, pop_stack, get_min_val, get_max_val的操作,YY了一下,中午吃饭的时候把代码写了,发一贴,算是正式刷题之前的一些预备工作吧。
- #include <cstdio>
- #include <cmath>
- #include <cstdlib>
- #include <cstring>
- #include <ctime>
- using namespace std;
-
- const int MAX_INTEGER = 0x3f3f3f3f;
- const int MAX_STACKSIZE = 100000 + 10;
-
-
- void init_seed() {
- srand((unsigned)(time(NULL)));
- return ;
- }
-
- int get_random() {
- return rand() % MAX_INTEGER;
- }
-
- int src_stack[MAX_STACKSIZE], maxVal[MAX_STACKSIZE], minVal[MAX_STACKSIZE];
- int min_Val, max_Val, src_index, min_index, max_index;
-
- void init_stack() {
- src_index = max_index = min_index = 0;
- min_Val = MAX_INTEGER; max_Val = -MAX_INTEGER;
- }
-
- void push_stack(int val) {
- src_stack[src_index++] = val;
- if(min_Val > val) {
- min_Val = val;
- }
- minVal[min_index++] = min_Val;
- if(max_Val < val) {
- max_Val = val;
- }
- maxVal[max_index++] = max_Val;
- return ;
- }
-
- void pop_stack() {
- if(src_index <= 0) {
- printf("The stack is empty!\n");
- return ;
- }
- src_index--, max_index--, min_index--;
- return ;
- }
-
- int get_min_val() {
- if(min_index <= 0) return -1;
- return minVal[min_index-1];
- }
-
- int get_max_val() {
- if(max_index <= 0) return -1;
- return maxVal[max_index-1];
- }
-
- int main() {
-
-
- #ifdef sponge_wxy
- freopen("aa.in", "r", stdin);
- freopen("bb.out", "w", stdout);
- #endif
-
-
- init_seed();
- init_stack();
-
- push_stack(1);
- printf("The max value is : %d\n", get_max_val());
- printf("THe min val is: %d\n", get_min_val());
- push_stack(2);
- printf("The max value is : %d\n", get_max_val());
- printf("THe min val is: %d\n", get_min_val());
- push_stack(2);
- printf("The max value is : %d\n", get_max_val());
- printf("THe min val is: %d\n", get_min_val());
- push_stack(3);
- printf("The max value is : %d\n", get_max_val());
- printf("THe min val is: %d\n", get_min_val());
- pop_stack();
- printf("The max value is : %d\n", get_max_val());
- printf("THe min val is: %d\n", get_min_val());
- pop_stack();
- printf("The max value is : %d\n", get_max_val());
- printf("THe min val is: %d\n", get_min_val());
- pop_stack(); pop_stack();
- printf("The max value is : %d\n", get_max_val());
- printf("THe min val is: %d\n", get_min_val());
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。