您的位置:首页 > 其它

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

2017-07-21 18:39 204 查看
实现一个栈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; //没有出现两个字符的情况
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐