力扣---2020.6.2

面试题64. 求1+2+…+n

class Solution {
    public int sumNums(int n) {
        int sum = n;
        boolean flag = n>0 && (sum += sumNums(n-1))>0;
        return sum;
    }
}

面试题 16.11. 跳水板

class Solution {
    public int[] divingBoard(int shorter, int longer, int k) {
        if(k<1){
            return new int[]{};
        }
        if(shorter == longer){
            return new int[]{shorter*k};
        }
        int[] res = new int[k+1];
        for(int i = 0;i<=k;i++){
            res[i] = longer*i + shorter*(k-i);
        }
        return res;
    }
}

面试题 17.06. 2出现的次数

//超时了.....hahah
class Solution {
    int count = 0;
    public int numberOf2sInRange(int n) {
        for(int i = 0;i <= n;i++){
            count2s(i);
        }
        return count;
    }

    public void count2s(int n){
        String s = n + "";
        for(int i = 0;i < s.length();i++){
            if(s.charAt(i)=='2'){
                count++;
            }
        }
    }
}
//超时(没有处理数字大小超过10^8)
class Solution {
    public int numberOf2sInRange(int n) {
        int count = 0;
        for(int i = 0;i<=n;i++){
            int res = i;
            while(res!=0){
                if(res%10==2){
                    count++;
                }
                res = res/10;
            }
        }
        return count;
    }
}
class Solution {
    public int numberOf2sInRange(int n) {
        if(n == 0) {
            return 0;
        }
        int digit = (int)Math.log10(n) + 1;
        int[][] dp = new int[digit+1][2];  
        // dp[i][0] = numberOf2sInRange(n % pow(10, i)) 保存0~n的1-i位组成的数包含2的个数
        // dp[i][1] = numberOf2sInRange(99..9) 保存i位均为9包含2的个数
        dp[1][0] = n % 10 >= 2 ? 1:0;
        dp[1][1] = 1;
        for(int i = 2; i <= digit; i++) {
            int k = n/ ((int)Math.pow(10, i-1)) % 10;
            dp[i][0] = k * dp[i-1][1] + dp[i-1][0];
            if(k == 2) {
                dp[i][0] += n % (int)Math.pow(10, i-1) +1; 
            } else if(k > 2){
                dp[i][0] +=  (int)Math.pow(10, i-1);
            }
            dp[i][1] = 10 * dp[i-1][1] + (int)Math.pow(10, i-1); //计算1-i位均为9的值包含2的个数
        }
        return dp[digit][0];
    }
}
class Solution {
    public int numberOf2sInRange(int n) {
        int ans=0;
        for(long i=1;i<=n;i*=10){
            int temp=(int) (n/i);
            int cur=temp%10;
            int temp1=temp/10;
            int temp2=(int) (n%i);
            ans+=(int) (temp1*i);
            if(cur==2) ans+=temp2+1;
            if(cur>2) ans+=i;
        }
        return ans;
    }
}

你知道的越多,你不知道的越多。

你可能感兴趣的:(数据结构与算法)