题目121 买卖股票的最佳时机
在写写写逐渐熟悉了各种语法之后,遇到了一道思路很有趣的题
第一种
暴力解法需要两层for循环
第二种
一边遍历一边存储当前最低的price和最大的差值,复杂度很低,但缺陷是如果需要知道最大利润对应哪一天就不行了~并且官方答案代码不太有助于厘清思路,改了改
class Solution{//solution只能首字母大写,全小写运行会报错
public:
int maxProfit(vector<int>&prices){ //vector<int>& "space" prices: without "space" is ok
int s = prices.size();
int inf = 1e9;
int minprice = inf, maxProfit = 0;
for(int price : prices){ //initial price in "for"
minprice = min(minprice, price);
maxProfit = max(maxProfit, price-minprice);
}
return maxProfit;
}
};
//作者:LeetCode-Solution +qsdn
//链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-//stock/solution/121-mai-mai-gu-piao-de-zui-jia-shi-ji-by-leetcode-/
//来源:力扣(LeetCode)著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目36.有效数独
相关说明直接放注释了_(:з」∠)_ 发现从自己提交记录里面复制不会带水印耶
class Solution{
public:
bool isValidSudoku(vector<vector<char>>& board){ //vector<vector<char>>&
int rows[9][9];//int rows[9][9]; without '=' !!!!!
int columns[9][9];
int subboxes[3][3][9];
// 在前面不止一次说过,定义变量时一定要进行初始化,尤其是数组和结构体这种占用内存大的数据结构。
// 在使用数组的时候经常因为没有初始化而产生“烫烫烫烫烫烫”这样的野值,俗称“乱码”。
// memset() 的作用是在一段内存块中填充某个给定的值。
// sizeof(subboxes)当操作数具有数组类型时,其结果是数组的总字节数。
//或者: int rows[9][9]={0};
// int columns[9][9]={0};
// int subboxes[3][3][9]={0};
memset(rows, 0, sizeof(rows));
memset(columns, 0, sizeof(columns));
memset(subboxes, 0, sizeof(subboxes));
char c = '0';//char c
int index = 0;//int index
for (int i = 0; i < 9; i++){
for (int j = 0; j < 9; j++){
c = board[i][j];
if (c != '.'){ //若c有值
//c - '0':通常我们在编程的时候,用字符转化为数字的时候经常要用到
index = c - '0' - 1;
rows[i][index]++;
columns[index][j]++;
subboxes[i/3][j/3][index]++; //[i/3][j/3][index]
//遍历的时候就顺便判断了,不用最后再循环一遍
// '|' and '||' are both ok!
if ( rows[i][index] > 1 | columns[index][j] > 1 | subboxes[i/3][j/3][index] > 1){
return false;
}
}
}
}
return true;
}
}; //';' is a must
题目73.矩阵置零
class Solution{
public:
void setZeroes(vector<vector<int>>& matrix){
int m = matrix.size(); //矩阵行数
int n = matrix[0].size(); //矩阵列数
bool ret[m];
bool col[n];
memset(ret, 0, m * sizeof(bool));
memset(col, 0, n * sizeof(bool));
//初始化时,bool r[9]={0}可以;bool row[m]={0}报错variable-sized object may not be initialized,因为m不确定,不能赋值,所以答案【只定义不赋值】,或者保险起见用【memset】
//或者 vector<int> row(m), col(n); //后续还是赋值true,但我不理解,明明是个int啊
for (int i = 0; i < m; i++){
for(int j = 0; j < n; j ++){
if (matrix[i][j]==0){ //或者if (!matrix[i][j])
ret[i] = col[j] = true;
}
}
}
for (int i = 0; i < m; i++){
for(int j = 0; j < n; j ++){
if (ret[i] || col[j] ){
matrix[i][j]=0;
}
}
}
// return matrix;
}
};
有一些疑问,先放着。。。