时隔一年,开始重新关注LC,进行复健活动

题目比较简单,宝刀未老只能说
知识点:模拟
、位运算
复杂度:O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public: int minChanges(int n, int k) { int cnt = 0; for(int i = 0;i < 32;i++) { if((((n >> i) & 1) == 1) && (((k >> i) & 1) == 0)) { n ^= 1 << i; cnt += 1; } } if(n==k){ return cnt; } return -1; } };
|
反思:
- 语法上,优先级忘了
- 常用的位运算,符号含义忘了
知识点:归纳
复杂度:O(n)
对不同情况进行模拟,脑内简化
1 2 3 4 5 6 7 8 9 10 11
| class Solution { public: bool doesAliceWin(string s) { int cnt = 0; for(char x : s) { if(x == 'a' || x == 'e' || x=='i' || x=='o' || x=='u') cnt++; } return cnt > 0; } };
|
反思:
- 归纳速度较慢,少算了情况(数据集中没有给出)
知识点:前缀/后缀和
复杂度:O(n)
进行contribution后,发现从后往前扫,每遇到一个0,对答案的贡献为前面1的个数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public: int maxOperations(string s) { int ans = 0; int cnt = 0; bool lft = false; for(char x : s){ if(x=='1') cnt++; } for(int i = s.size()-1;i >= 0;i--) { if(s[i]=='0' && !lft) ans += cnt, lft = true; if(s[i]=='1') cnt--, lft = false; } return ans; } };
|
知识点:归纳、单调栈
复杂度:O(n)
首先,明确操作的对象,即两者之差
其次,利用类似“接雨水”的方式思考贡献,问题转换为求山峰之间最低的pos,作为能够“复用”的点,然后剩下的每个山峰只能自己消自己的,代价为最高点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { public: long long minimumOperations(vector<int>& nums, vector<int>& target) { int n = nums.size(); vector<long long> diff(n,0); for(int i = 0;i < n;i++) { diff[i] = target[i] - nums[i]; } long long ans = abs(diff[0]); int lst = diff[0]; for(int i = 1; i < diff.size();i++) { int x = diff[i]; if(x > 0) { if(x > lst) { ans += x - max(0,lst); } }else{ if(x < lst) { ans += -x - max(0,-lst); } } lst = x; } return ans; } };
|