3.18

简易银行系统

thinking

模拟…

solution

class Bank {
public:
    using ll=long long;
    vector<ll> a;
    int n;
    Bank(vector<long long>& balance) {
        a=balance;
        n=balance.size();
    }
    
    bool transfer(int a1, int a2, long long money) {
        if(a1>n||a1<=0||a2>n||a2<=0||a[a1-1]<money) return false;
        a[a1-1]-=money;
        a[a2-1]+=money;
        return true;
    }
    
    bool deposit(int account, long long money) {
        if(account>n||account<=0) return false;
        a[account-1]+=money;
        return true;
    }
    
    bool withdraw(int account, long long money) {
        if(account>n||account<=0||a[account-1]<money) return false;
        a[account-1]-=money;
        return true;
    }
};

青蛙跳台阶问题

thinking

简单线性dp

solution

class Solution {
public:
    int mod=1e9+7;
    int numWays(int n) {
        if(n==0||n==1) return 1;
        if(n==2) return 2;
        vector<long long> dp(n+1);
        dp[0]=1;
        dp[1]=1;
        dp[2]=2;
        for(int i=3;i<=n;++i) {
            dp[i]=dp[i-1]+dp[i-2];
            dp[i]%=mod;
        }
        return (int)dp[n];
    }
};

前 n 个数字二进制中 1 的个数

thinking

模拟

solution

class Solution {
public:
    vector<int> countBits(int n) {
        vector<int> a(n+1);
        for(int i=0;i<=n;++i) {
            int cnt=0;
            int num=i;
            while(num) {
                if((num)&1==1) ++cnt;
                num>>=1;
            }
            a[i]=cnt;
        }
        return a;
    }
};

下载插件

thinking

换一个思路,我们查找时间为t的时候,最大能够打印额字数,返回在t-1到t的时间段内的数据对应的t即可。

solution

class Solution {
public:
    int leastMinutes(int n) {
        int t=1;
        int maxn=1;
        while(maxn<n) {
            ++t;
            maxn*=2;
        }
        return t;
    }
};
posted @ 2022-03-19 11:58  圣道  阅读(101)  评论(0)    收藏  举报