1523 | Count Odd Numbers in an Interval Range
https://leetcode.com/problems/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
작성 코드
sum 이용 (실패)
class Solution:
def countOdds(self, low: int, high: int) -> int:
nums = [num for num in range(low, high + 1) if num % 2 == 1]
return len(nums)
- 시간 초과!
패턴 파악 (통과)
class Solution:
def countOdds(self, low: int, high: int) -> int:
if low % 2 == 0 and high % 2 == 0:
return (high - low) // 2
if low % 2 == 1 and high % 2 == 1:
return 2 + (high - low - 1) // 2
else:
return (high - low) // 2 + 1
- 시작과 종료가 각각 홀수, 짝수일 때를 나누어 계산
이상 코드
class Solution:
def countOdds(self, low, high):
return (high + 1) // 2 - low // 2
- 깔끔 !!
- 패턴 파악을 잘 해야 되는 문제인데 수학 !
- 짝수는 -> 1 ~ n 까지라면, n - (n + 1) // 2 --> n 에서 홀수의 개수를 뺌
반응형
'Algorithm > LeetCode' 카테고리의 다른 글
| [LeetCode] 300 | Longest Increasing Subsequence (0) | 2023.03.31 |
|---|---|
| [LeetCode] 896 | Monotonic Array (0) | 2023.03.29 |
| [LeetCode] 217 | Contains Duplicate (0) | 2023.03.09 |
| [LeetCode] 1588 | Sum of All Odd Length Subarrays (0) | 2022.07.05 |
| [LeetCode] 226 | Invert Binary Tree (0) | 2022.05.30 |
댓글