题目一
思路
简单模拟,遇到数字就开始计数,一旦出去数字区域了,和之前记录的前导数字比较,不是严格递增则错,严格递增则继续向下统计。
代码
注:一定要加一个状态,记录一下,当前进入了非数字区域,用不用和之前pre数字比较,看是否严格递增。
class Solution {
public:
int pre = -1;//前导数字
int now = 0;//用于拼当前数字
bool is_judge = false;//用不用和前导数字比
bool judge() {
if (!is_judge) {
//false需要比较
if (pre == -1) {
//第一次出现数字
pre = now;//更新
now = 0;
is_judge = true;
}
else {
if (now <= pre) {
return false;//不满足题意
}
pre = now;
now = 0;
is_judge = true;
}
}
return true;
}
bool areNumbersAscending(string s) {
int sizes = s.size();
for (int i = 0; i <= sizes; i++) {
if ((s[i] >= '0'&&s[i] <= '9')) {
//遇到数字开始拼
now = now * 10 + (s[i] - '0');
is_judge = false;
}
else {
if (!judge()) {
//返回来true,说明满足题意
return false;
}
}
}
if (!judge()) {
//多比较一次,防止最后组成的数字没比较上
return false;
}
return true;
}
};
(所有代码均已在力扣上运行无误)
经测试,该代码运行情况是(经过多次测试所得最短时间):
时间复杂度O(N)
题目二
力扣:5903. 简易银行系统
思路
直接按照题意模拟
1、一定注意,取钱时先判断有没有那么多,
2、优先判断,该用户是否存在
代码
class Bank {
public:
Bank(vector<long long>& balance) {
int n = balance.size();
for (int i = 0; i < n; i++) {
//初始化
this->balance[i + 1] = balance[i];
}
this->n = this->balance.size();
}
bool no_user(int n1) {
//判断用户是否合法
if (n1<1 || n1>this->n) {
return true;
}
return false;
}
bool transfer(int account1, int account2, long long money) {
if (no_user(account1) || no_user(account2)) {
//判断用户是否合法
return false;
}
if (balance[account1] >= money) {
balance[account1] -= money;
balance[account2] += money;
return true;
}
return false;
}
bool deposit(int account, long long money) {
if (no_user(account)) {
//判断用户是否合法
return false;
}
balance[account] += money;
return true;
}
bool withdraw(int account, long long money) {
if (no_user(account)) {
//判断用户是否合法
return false;
}
if (balance[account] >= money) {
balance[account] -= money;
return true;
}
return false;
}
private:
int n;
unordered_map<int, long long> balance;
};
(所有代码均已在力扣上运行无误)
经测试,该代码运行情况是(经过多次测试所得最短时间):
题目三
思路
直接模拟
1、用DFS求出每个子集,求的时候,关键就是每个元素在或者不在。
2、对子集遍历求各个元素取或的和,但是一定注意,这个子集不能是空。
代码
class Solution {
public:
int maxs = 0;
int ans = 0;
vector<int> nums;
int n = 0;
void dfs(int i, vector<int> tmp) {
if (i == n) {
int n1 = tmp.size();
if(n1>0){
//绝对不能搞空集
int item = 0;
for (int i = 0; i < n1; i++) {
item |= tmp[i];
}
if (item > maxs) {
//动态统计
maxs = item;//更新最大值
ans = 1;//更新数量
}
else if (item == maxs) {
ans++;
}
}
return;
}
tmp.push_back(nums[i]);//元素i在
dfs(i + 1, tmp);
tmp.pop_back();//元素i不在
dfs(i + 1, tmp);
}
int countMaxOrSubsets(vector<int>& nums) {
this->nums = nums;
this->n = nums.size();
vector<int> tmp;
dfs(0, tmp);
return ans;
}
};
(所有代码均已在力扣上运行无误)
经测试,该代码运行情况是(经过多次测试所得最短时间):