일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- LinkedList
- Java
- VCS
- Two Pointers
- hash table
- 자료구조
- greedy
- 구현
- A* Algorithm
- sorting
- BFS
- Leedcode
- stack
- SinglyLinkedList
- Bellman-Ford
- dfs
- String
- 광연자동차운전면허학원
- heap
- leetcode
- Union Find
- hash
- DailyLeetCoding
- ArrayList vs LinkedList
- Easy
- python3
- Hashtable
- Medium
- graph
- array
- Today
- Total
Min IT's Devlog
[python3] 1523. Count Odd Numbers in an Interval Range 본문
[python3] 1523. Count Odd Numbers in an Interval Range
egovici 2023. 2. 13. 19:51풀이 일자: 23.02.13
난이도: [Easy]
분류: [Math]
문제 내용
2개의 양수가 주어졌을 때 그 수들을 포함한 그 사이의 수들 중 홀수의 개수를 구하는 문제이다.
문제 해결 흐름
1. 별다른 알고리즘 보다는 어떤 수학적인 패턴을 찾아서 구해내는 것이 맞겠다.
→ 짝수부터 세는 경우 ( high - low )//2 + 1개의 홀수가 나온다.
class Solution:
def countOdds(self, low: int, high: int) -> int:
if (low & 1) == 0:
low += 1;
return 0 if low > high else (high - low)// 2 + 1;
Time Complexity: O(1)
반복문 돌아가는 것 없이 계산만 진행하기에 O(1)이다.
Space Complexity: O(1)
주어진 파라미터 이외에 사용되는 것이 없기에 O(1)이다.
다른 해결 방식
수학적으로 푸는 방법이 출제자의 의도일 것이고 naive하게 푼다면 for문을 돌려서 홀수면 count하는 방식이 있을 것이지만 규칙성을 찾는다면 쉽게 파악할 수 있을 것이다.
문제 링크
https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/description/
Count Odd Numbers in an Interval Range - LeetCode
Can you solve this real interview question? 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 Explanati
leetcode.com
'코테 > LeetCode(Solve)' 카테고리의 다른 글
[python3] 1129. Shortest Path with Alternating Colors (0) | 2023.02.14 |
---|---|
[python3] 67. Add Binary (0) | 2023.02.14 |
[python3] 1162. As Far from Land as Possible (0) | 2023.02.10 |
[python3] 2306. Naming a Company (0) | 2023.02.09 |
[python3] 45. Jump Game II (0) | 2023.02.08 |