【每日一题-7】min栈实现与第一次只出现两次的字符

来源:互联网 发布:ps4淘宝被禁的游戏 编辑:程序博客网 时间:2024/05/29 11:47

实现一个栈Stack,要求实现Push(出栈)、Pop(入栈)、Min(返回最小值的操作)的时间复杂度为O(1)

#include<iostream>#include<stack>using namespace std;template<class T>class Stack{public:void Push(const T data){s1.push(data);int top = s1.top();if (s2.empty())s2.push(top);else{if (!s1.empty() && s1.top() < s2.top()){s2.push(s1.top());}s1.pop();}}void Pop(){if (!s1.empty()){s1.pop();}}int Min(){return s2.top();}protected:stack<int> s1;stack<int> s2;};

查找一个字符串中第一个只出现两次的字符。比如:“abcdefabcdefabc”中第一个只出现两次为‘d’,要求时间复杂度为O(N),空间复杂度为O(1)

#include<assert.h>char FindFirstCh(char* str, size_t n){assert(str&& n);char arr[256] = { 0 };//记录字符出现的个数int count[256] = { 0 };//记录字符出现的次数for (size_t i = 0; i < n; i++){arr[str[i]]++;count[str[i]] = i;}for (size_t i = 0; i < n; i++){if (count[i] && arr[i] == 2)//如果该字符出现两次,且是第一次出现的return arr[i];}return NULL;//没有出现两个字符的情况}

阅读全文
0 0
原创粉丝点击