今天的算法内容是:栈
一、 每日一题
- 这道题的n好像没什么用
- 这道题是单调递增的
- 哈希表:先创建一个哈希表并初始化为0,每一个在target当中出现的数字标记为1
- 先全部'push'一遍,然后哈希表中为0的值'pop'
class Solution {
public:
vector<string> buildArray(vector<int>& target, int n) {
int index = 0;
int limit = target.back();//target的最后一个元素
int hash[101];
memset(hash, 0, sizeof(hash));
vector<string> ret;
for(int i = 0; i < target.size(); ++i) {
hash[target[i]] = 1;
}
for(int i = 1; i <= limit; ++i) {
ret.push_back("Push");
if(!hash[i]) {
ret.push_back("Pop");
}
}
return ret;
}
};
- 用stktop变量去判断是不是完整的一组括号
- 如果是完整的一组括号,只取内层的括号。内层如果没有就是空字符串
- pre = i+1 跳到下一组括号,再进行判断,最后返回答案
class Solution {
public:
string removeOuterParentheses(string s) {
string ans;
int stktop = 0;
int pre = 0;
for(int i = 0; i < s.size(); ++i) {
if(s[i] == '(') {
++stktop;
}else {
--stktop;
}
//当碰到完整的括号的时候
if(stktop == 0) {
for(int j = pre+1; j <= i-1; ++j) {
ans += s[j];
}
//判断下一组括号
pre = i+1;
}
}
return ans;
}
};
- 两个变量istu和isand分别记录学生和三明治数组的索引
- 如果索引值相等,就都加1再比较下一组数据;如果不相等,就把学生的索引值的值加到学生数组的尾端,并且索引值加1.
- 要注意的是,需要添加一个limit,用来跳出循环,否则会无限循环下去
- 返回值是学生数组的长度减去学生的索引值。
class Solution {
public:
int countStudents(vector<int>& students, vector<int>& sandwiches) {
int istu = 0;
int isand = 0;
int limit = 0;
while(istu < students.size() && isand < sandwiches.size()) {
if(students[istu] == sandwiches[isand]) {
isand++;
istu++;
}else{
students.push_back(students[istu]);
istu++;
if(limit++>200) break;
}
}
return students.size()-istu;
}
};
- 用一个数组表示栈的思想
- 用变量top表示栈顶,变量size表示栈的最大长度
class CustomStack {
public:
int top, size;
int *stk;
CustomStack(int maxSize) {
stk = new int[maxSize+1];
size = maxSize;
top = 0;
}
void push(int x) {
if(top < size) {
stk[top++] = x;
}
}
int pop() {
if(top == 0) {
return -1;
}
top--;
return stk[top];
}
void increment(int k, int val) {
if(top < k) {
for(int i = 0; i < top; ++i) {
stk[i] += val;
}
} else {
for(int i = 0; i < k; ++i) {
stk[i] += val;
}
}
}
};
浙公网安备 33010602011771号