LeetCode-单调栈

739. 每日温度

  • 简单,通过单调栈,弹出栈中小于当前元素的元素,可以找到弹出元素的第一个大于其的位置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
stack<int> monoStk;
int len = temperatures.size();
vector<int> res(len);
for(int i = 0; i < len; i++) {
while(!monoStk.empty() && temperatures[monoStk.top()] < temperatures[i]) {
int top = monoStk.top();
res[top] = i - top;
monoStk.pop();
}
monoStk.push(i);
}
return res;
}
};

42. 接雨水

AC1

思路

阅读更多

LeetCode-位运算

位运算常见技巧

  • 位运算计算
a op b res
x xor 0x00 x
x xor 0xff ~x
x xor x 0
x and 0x00 0
x and 0xff x
x and x x
x or 0x00 x
x or 0xff 0xff
x or x x
x and x-1 去掉最低位
x and -x 得到最低位
  • 状态压缩

用二进制位表示状态

268. 丢失的数字

阅读更多

LeetCode-dp

leetcode 101的动态规划专题

基本动态规划:一维

70. 爬楼梯

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int climbStairs(int n) {
int a=1,b=2;
if(n<2) return 1;
for(int i = 2; i <n ; i++) {
int c = a+b;
a=b;
b=c;
}
return b;
}
};

dp数组表示上n层楼有几种可能
转移方程是 $ dp[i] = dp[i-1] + dp[i-2] $
上到第i层有可能从第i-1层或i-2层上来,则上到i层的可能数目就是 $ dp[i-1] + dp[i-2] $
由于dp[i]只需要前两个数的数据,所以可以优化掉dp数组,用两个变量代替,节省数组空间

198. 打家劫舍

阅读更多