LeetCode-在区间范围内统计奇数数目
题目
给你两个非负整数 low 和 high 。请你返回 low 和 high 之间(包括二者)奇数的数目。
示例 1:
输入:low = 3, high = 7
输出:3
解释:3 到 7 之间奇数数字为 [3,5,7] 。
示例 2:
输入:low = 8, high = 10
输出:1
解释:8 到 10 之间奇数数字为 [9] 。
官方题解
如果我们暴力枚举 [low,high] 中的所有元素会超出时间限制。
我们可以使用前缀和思想来解决这个问题,定义 pre(x) 为区间 [0,x] 中奇数的个数,很显然:

故答案为 pre(high)−pre(low−1)。
class Solution {
public int countOdds(int low, int high) {
return pre(high) - pre(low - 1);
}
public int pre(int x) {
return (x + 1) >> 1;
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/count-odd-numbers-in-an-interval-range/solutions/371283/zai-qu-jian-fan-wei-nei-tong-ji-qi-shu-shu-mu-by-l/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
我的解答
class Solution {
public int countOdds(int low, int high) {
int count=(high-low)/2;
if(low%2==1){
count++;
}
else if(high%2==1){
count++;
}
return count;
}
}
思考
- 里面涉及到数学概念:前缀和,还要左闭区间的减法规则。这是我不清楚的。
- 挫败感比较重,AI时代,夯实基础还有没有必要?

浙公网安备 33010602011771号