前言
一个本硕双非的小菜鸡,备战24年秋招,计划刷完hot100和剑指Offer的刷题计划,加油!
根据要求,每一道题都要写出两种以上的解题技巧。
一、31. 下一个排列(HOT100)
31. 下一个排列
Note:
- 我们需要将一个左边的「较小数」与一个右边的「较大数」交换,以能够让当前排列变大,从而得到下一个排列。
- 同时我们要让这个「较小数」尽量靠右,而「较大数」尽可能小。当交换完成后,「较大数」右边的数需要按照升序重新排列。这样可以在保证新排列大于原来排列的情况下,使变大的幅度尽可能小。
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int size = nums.size();
int i = size - 2;
if (size == 1) return;
//寻找第一个降序区间,这就是左节点
while (i >= 0 && nums[i] >= nums[i + 1])
i--;
if (i >= 0) {
//寻找刚才的升序区间的最小值,即为右节点
int j = size - 1;
while (j >= 0 && nums[i] >= nums[j])
j--;
swap(nums[i], nums[j]);
}
reverse(nums.begin() + i + 1, nums.end());
}
};
Note:从右往左,右边正序排列,当前值如果大于等于右边最大值,将当前值加入右侧排列,如果小于右边最大值,则当前值和右边第一个大于当前值的位置互换。
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int size = nums.size();
if (size < 2) return;
for (int i = nums.size() - 2; i >= 0; i--) {
if (nums[i] >= nums[size - 1]) { //当前值如果大于等于右边最大值,将当前值加入右侧排列,
for (int j = i; j < size - 1; j++) {
swap(nums[j], nums[j + 1]);
}
} else if (nums[i] < nums[size-1]) { //如果小于右边最大值,则当前值和右边第一个大于当前值的位置互换。
for (int j = i+1; j < size; j++) {
if (nums[i] < nums[j]) {
swap(nums[i], nums[j]);
return;
}
}
}
}
}
};
二、9. 用两个栈实现队列(剑指Offer)
Note:这题也没啥两种方法,需要两个栈一个输入栈,一个输出栈。
在push数据的时候,只要数据放进输入栈就好,但在pop的时候,操作就复杂一些,输出栈如果为空,就把进栈数据全部导入进来(注意是全部导入),再从出栈弹出数据,如果输出栈不为空,则直接从出栈弹出数据就可以了。
如果进栈和出栈都为空的话,说明模拟的队列为空了。
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stIn.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if (stOut.empty()) {
while(!stIn.empty()) {
stOut.push(stIn.top());
stIn.pop();
}
}
int res = stOut.top();
stOut.pop();
return res;
}
/** Get the front element. */
int peek() {
int res = this->pop();
stOut.push(res);
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return stIn.empty() && stOut.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* bool param_4 = obj.empty();
*/
Note:用队列实现栈
还是要用两个队列来模拟栈,只不过没有输入和输出的关系,而是另一个队列完全用来备份的
class MyStack {
public:
queue<int> que1;
queue<int> que2;
MyStack() {
}
void push(int x) {
que1.push(x);
}
int pop() {
int size = que1.size();
size--;
while (size--) {
que2.push(que1.front());
que1.pop();
}
int res = que1.front();
que1.pop();
que1 = que2;
while (!que2.empty()) {
que2.pop();
}
return res;
}
int top() {
return que1.back();
}
bool empty() {
return que1.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
总结
祝大家都能学有所成,找到一份好工作!