文章目录
1.surrounded-regions(leetcode 130)
给定一个二维的矩阵,包含 ‘X’ 和 ‘O’(字母 O)。
找到所有被 ‘X’ 围绕的区域,并将这些区域里所有的 ‘O’ 用 ‘X’ 填充。
class Solution {
public:
void dfs(vector<vector<char>>& board, int row, int column){
if(row<0 || column<0 || row>=board.size()||column>=board[0].size()||board[row][column]=='X'||board[row][column]=='#')
return ;
board[row][column] = '#';
dfs(board,row-1,column);//up
dfs(board,row+1,column);//down
dfs(board,row,column-1);//left
dfs(board,row,column+1);//right
}
void solve(vector<vector<char>>& board) {
if(board.empty())
return;
int row = board.size();
int column = board[0].size();
for(int i=0;i<row;++i){
for(int j=0;j<column;++j){
bool isedge = i==0 || j==0 || i==row-1 || j==column-1;
if(isedge && board[i][j]=='O')
dfs(board,i,j);
}
}
for(int i=0;i<row;++i){
for(int j=0;j<column;++j){
if(board[i][j]=='#')
board[i][j]='O';
else if(board[i][j]=='O')
board[i][j]='X';
}
}
}
};
2. longest-consecutive-sequence(leetcode 128)
给定一个无序的整数类型数组,求最长的连续元素序列的长度。
例如:
给出的数组为[100, 4, 200, 1, 3, 2],最长的连续元素序列为[1, 2, 3, 4]. 返回这个序列的长度:4
你需要给出时间复杂度在O(n)之内的算法
class Solution {
public:
int longestConsecutive(vector<int> &num) {
if(num.empty()) return 0;
int res = 0;
unordered_set<int> hash(num.begin(),num.end());
for(int val: num){
int last = val;
if(hash.find(last-1)==hash.end()){
while(hash.erase(last)) ++last;
res = max(res,last-val);
}
}
return res;
}
};
hash表的应用小技巧,每次判断该点是否是有序序列的首元素,若是的话就将这个相关的整个有序序列删除掉,然后找其他的有序子序列,最终得出最大值即可。
3.best-time-to-buy-and-sell-stock(leetcode 121)
买卖股票的最佳时机:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int maxprofit = 0;
int minprice = INT32_MAX;
for(int i=0;i<prices.size();++i){
if(minprice > prices[i])
minprice = prices[i];
else if(prices[i]-minprice > maxprofit)
maxprofit = prices[i]-minprice;
}
return maxprofit;
}
};
4.best-time-to-buy-and-sell-stock-ii(leetcode 122)
买卖股票的最佳时机 II给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
class Solution {
public://峰谷法
int maxProfit(vector<int>& prices) {
if(prices.empty()) return 0;
int res = 0;
int valley ;
int peak ;
for(int i=0;i<prices.size()-1;){
while(i<prices.size()-1 && prices[i]>=prices[i+1])
++i;
valley = prices[i];
while(i<prices.size()-1 && prices[i]<=prices[i+1])
++i;
peak = prices[i];
res += peak-valley;
}
return res;
}
};
5.convert-sorted-array-to-binary-search-tree(leetcode 108)
给出一个升序排序的数组,将其转化为平衡二叉搜索树(BST)
class Solution {
public:
TreeNode* Build(vector<int>& nums, int low, int high){
if(low>high)
return NULL;
int mid = (low+high)/2;
if ((low + high) % 2 == 1) ++mid;//这个要注意,否则过不去
TreeNode* root = new TreeNode(nums[mid]);
root->left = Build(nums,low,mid-1);
root->right = Build(nums,mid+1,high);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.empty())
return NULL;
TreeNode *root = Build(nums,0,nums.size()-1);
return root;
}
};