leetcode 编程能力入门

leetcode 编程能力入门,第1张

目录

1 在区间范围内统计奇数数目

2 去掉最低工资和最高工资后的工资平均值


1 在区间范围内统计奇数数目

解题思路是将low与high分为奇-奇、奇-偶、偶-偶、偶-奇四种类型,除了偶-偶num=(high-low)//2以外,其余都是num = (high-low)//2 +1

class Solution:
    def countOdds(self, low: int, high: int) -> int:
        num = (high - low)//2
        if not ((high % 2 == 0) and (low % 2 == 0)):
            num += 1
        return num
class Solution {
public:
    int countOdds(int low, int high) {
        int num = (high - low) / 2;
        if (!((high % 2 == 0) && (low % 2 == 0)))
        {
            num++;
        }
        return num;
    }
};

c++的与&&或 ||非!

2 去掉最低工资和最高工资后的工资平均值
class Solution:
    def average(self, salary: List[int]) -> float:
        max_salary = max(salary)
        min_salary = min(salary)
        average_salary = (sum(salary) - max_salary - min_salary) / (len(salary) - 2)
        return average_salary
class Solution:
    def average(self, salary: List[int]) -> float:
        sum_salary = max_salary = 0
        min_salary = 1000001
        for i in salary:
            if max_salary < i:
                max_salary = i
            if min_salary > i:
                min_salary = i
            sum_salary += i
        average_salary = (sum_salary - min_salary - max_salary) / (len(salary) - 2)
        return average_salary
class Solution {
public:
    double average(vector& salary) {
        double sum_salary = 0;
        int max_salary = 0;
        int min_salary = 1000001;
        for (int i=0; i salary[i]) min_salary = salary[i];
            sum_salary += salary[i];
        }
        double average_salary = (sum_salary - min_salary -max_salary) / (salary.size() - 2);
        return average_salary;
    }
};
class Solution {
public:
    double average(vector& salary) {
        double maxValue = *max_element(salary.begin(), salary.end());
        double minValue = *min_element(salary.begin(), salary.end());
        double sum = accumulate(salary.begin(), salary.end(), - maxValue - minValue);
        return sum / int(salary.size() - 2);
    }
};

设置两个flag分别标志最大值和最小值,最后求和的时候减去这两个值,题目给出了工资范围,要注意最大值的初始值要比最小值小,最小值的初始值要比最大值大。直接调用函数就能通过

accumulate用法:accumulate(arr.begin(), arr.end(), int val);其中val是初始值

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/707142.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-24
下一篇 2022-04-24

发表评论

登录后才能评论

评论列表(0条)

保存