刷题(一)
1.数字统计
解法:枚举+数字拆分(模10、除以10)
#include <iostream>
using namespace std;int main() {int L = 0;int R = 0;cin >> L >> R;int ret = 0;for(int i = L;i <= R;i++){int j = i;while(j){if(j % 10 == 2)ret++;j /= 10;}}cout << ret << endl;return 0;
}
2. 两个数组的交集
解法:哈希
class Solution {
public:bool hash[1010] = {0};vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {vector<int> tmp;for(auto x:nums1){hash[x] = true;}for(auto x:nums2){if(hash[x]){tmp.push_back(x);hash[x] = false;}}return tmp;}
};
3. 点击消除
解法:栈
细节:用可边长的数组(string),来模拟栈
#include <iostream>
#include <string>
using namespace std;int main() {string s;cin >> s;string st;for(auto ch : s){if(st.size() && st.back() == ch){st.pop_back();}else{st.push_back(ch);}}cout << (st.size() == 0 ? "0" : st ) << endl;return 0;
}