刷题第四天
1、螺旋矩阵
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if(matrix.size() == 0) return res;
int rows = matrix.size() - 1;
int cols = matrix[0].size() - 1;
int row = 0, col = 0;
while(1){
for(int i = col; i <= cols; i++) res.push_back(matrix[row][i]);
if(++row > rows) break;
for(int i = row; i <= rows; i++) res.push_back(matrix[i][cols]);
if(--cols < col) break;
for(int i = cols; i >= col; i--) res.push_back(matrix[rows][i]);
if(--rows < row) break;
for(int i = rows; i >= row; i--) res.push_back(matrix[i][col]);
if(++col > cols) break;
}
return res;
}
};
2、用栈实现队列
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
class MyQueue {
private:
stack<int> stack1, stack2;
void in2out(){
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(stack2.empty()){
in2out();
}
int x = stack2.top();
stack2.pop();
return x;
}
/** Get the front element. */
int peek() {
if(stack2.empty())
in2out();
return stack2.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return stack1.empty() && stack2.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
3、全排列
给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
class Solution {
public:
vector<vector<int>> res;
vector<int> tmp;
bool st[6];
void dfs(vector<int>& nums, int k){
if(nums.size() == tmp.size()){
res.push_back(tmp);
return;
}
for(int i = 0; i < nums.size(); i++){
if(!st[i]){
st[i] = true;
tmp.push_back(nums[i]);
dfs(nums, k + 1);
st[i] = false;
tmp.pop_back();
}
}
}
vector<vector<int>> permute(vector<int>& nums) {
dfs(nums, 0);
return res;
}
};
4、最大子序和
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int res = nums[0];
for(int i = 1; i < nums.size(); i++){
nums[i] += max(nums[i - 1], 0);
res = max(res, nums[i]);
}
return res;
}
};