[LeetCode] 1523. Count Odd Numbers in an Interval Range

Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).

Example 1:

Input: low = 3, high = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].

Example 2:

Input: low = 8, high = 10
Output: 1
Explanation: The odd numbers between 8 and 10 are [9].

Constraints:

  • 0 <= low <= high <= 10^9

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

给你两个非负整数 low 和 high 。请你返回 low 和 high 之间(包括二者)奇数的数目。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-odd-numbers-in-an-interval-range
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题看似简单但是直接用 for 循环做是会超时的。这里我提供两种优化的思路。

第一种思路是用数学的方法统计 low 和 high 之间有多少个奇数。注意Java中做除法的时候是向下取整,所以不 +1 的话就会漏掉结果,而 (high - low) / 2 的结果一定是偶数。

  • 如果 low 是奇数,那么两者之间的奇数个数是 (high - low) / 2 + 1,这里的 + 1 是为了不漏掉 low
  • 如果 high 是奇数,那么两者之间的奇数个数是 (high - low) / 2 + 1,这里的 + 1 是为了不漏掉 high
  • 如果两者都是偶数,那么两者之间的奇数个数是 (high - low) / 2

时间O(1)

空间O(1)

Java实现

 1 class Solution {
 2     public int countOdds(int low, int high) {
 3         if (low % 2 == 1) {
 4             return (high - low) / 2 + 1;
 5         }
 6         if (high % 2 == 1) {
 7             return (high - low) / 2 + 1;
 8         }
 9         return (high - low) / 2;
10     }
11 }

 

另一种思路类似前缀和。我们定义 pre(x) 为区间 [0, x] 中奇数的个数,那么我们可以得到 pre(x) = (x + 1) / 2 的值取下界。

那么为了求区间 [low, high] 中奇数的个数,我们可以通过求 pre(high) - pre(low - 1) 得到。

时间O(1)

空间O(1)

Java实现

1 class Solution {
2     public int countOdds(int low, int high) {
3         return pre(high) - pre(low - 1);
4     }
5 
6     public int pre(int x) {
7         return (x + 1) >> 1;
8     }
9 }

 

LeetCode 题目总结

posted @ 2022-02-07 14:02  CNoodle  阅读(209)  评论(0编辑  收藏  举报