最小栈
构造数据结构,能够满足普通栈的功能(入栈、出栈、栈顶),并且能够输出当前栈的最小元素。
https://leetcode-cn.com/problems/min-stack/
添加一个辅助栈,如果入栈的元素比辅助栈栈顶的元素还小,那么把辅助栈栈顶的元素入栈即可。
class MinStack {
public:
/** initialize your data structure here. */
stack miniStack; // 辅助最小栈
stack originStack;
MinStack() {
}
void push(int x) {
if (miniStack.empty() || x < miniStack.top()) {
miniStack.push(x);
} else {
miniStack.push(miniStack.top());
}
originStack.push(x);
}
void pop() {
if (!miniStack.empty()) {
miniStack.pop();
}
if (!originStack.empty()) {
originStack.pop();
}
}
int top() {
return originStack.top();
}
int getMin() {
return miniStack.top();
}
};
h指数
至多有 h 篇论文分别被引用了至少 h 次,求最大的h
https://leetcode-cn.com/problems/h-index/
贪心策略,将数组排序,遍历一次即可。
class Solution {
public:
int hIndex(vector& citations) {
sort(citations.begin(), citations.end());
int len = citations.size();
for(int i = 0; i < len; i++) {
if(len - i <= citations[i]){
return len - i;
}
}
return 0;
}
};
简化版的八数码问题
https://leetcode-cn.com/problems/sliding-puzzle/
由于要求最少移动次数,很容易想到用宽度优先搜索。
状态的表示可以把6个数字压缩成一个int。
class Solution {
public:
int slidingPuzzle(vector>& board) {
int dirs[4][2] = {{-1,0}, {1,0}, {0,1}, {0,-1}};
// 存储当前状态
map visited;
int tmp = 0;
int curx, cury;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == 0) {
curx = i, cury = j;
}
tmp = tmp * 10 + board[i][j];
}
}
visited[tmp] = true;
queue> que;
que.push(make_pair(tmp, 0));
// bfs
while (!que.empty()) {
pair cur = que.front();
que.pop();
int cur_state = cur.first;
int cur_step = cur.second;
if (cur_state == 123450) {
return cur_step;
}
// 寻找0的状态
int curx, cury, nextx, nexty, next_state;
int zero_pos = 0, next_pos, swap_item, tmp = cur_state;
while (tmp) {
if (tmp % 10 == 0) {
break;
}
tmp /= 10;
zero_pos++;
}
zero_pos = 5 - zero_pos;
curx = zero_pos / 3;
cury = zero_pos % 3;
// 遍历四个方向
for (int i = 0; i < 4; i++) {
nextx = curx + dirs[i][0];
nexty = cury + dirs[i][1];
if (nextx >= 0 && nextx < 2 && nexty >= 0 && nexty < 3) {
swap_item = cur_state;
if (nextx == 0) {
swap_item /= 1000;
}
if (nexty == 0) {
swap_item /= 100;
} else if (nexty == 1) {
swap_item /= 10;
}
swap_item %= 10;
next_state = cur_state + swap_item * pow(10, 5 - curx * 3 - cury) - swap_item * pow(10, 5 - nextx * 3 - nexty);
if (!visited[next_state]) {
visited[next_state] = true;
que.push(make_pair(next_state, cur_step + 1));
}
}
}
}
return -1;
}
};