[算法][差分][延迟相差][leetcode]2960. 统计已测试设备

题目地址:

https://leetcode.cn/problems/count-tested-devices-after-test-operations/description/


解法一:暴力解法

class Solution {
    
    
    public int countTestedDevices(int[] batteryPercentages) {
    
    
        //特殊条件判断
        if(null == batteryPercentages || batteryPercentages.length==0){
    
    
            return 0;
        }

        //记录结果
        int res=0;

        int n = batteryPercentages.length;

        for(int i=0; i<n;i++){
    
    
            if(batteryPercentages[i]>0){
    
    
                res++;
            }else{
    
    
                continue;
            }
            for(int j =i+1;j<n;j++){
    
    
               batteryPercentages[j]=Math.max(0, batteryPercentages[j] - 1);
            }
        }

        return res;
    }
}

解法二:差分法

  class Solution {
    
    

    public int countTestedDevices(int[] batteryPercentages) {
    
    
        //记录被减一的次数
        int d = 0;
        int res=0;
        for(int i : batteryPercentages){
    
    
            if(i-d>0){
    
    
                res++;
                d++;
            }
        }

        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/zhaoliubao1/article/details/138726481