• LeetCode每日一题(2438. Range Product Queries of Powers)


    Given a positive integer n, there exists a 0-indexed array called powers, composed of the minimum number of powers of 2 that sum to n. The array is sorted in non-decreasing order, and there is only one way to form the array.

    You are also given a 0-indexed 2D integer array queries, where queries[i] = [lefti, righti]. Each queries[i] represents a query where you have to find the product of all powers[j] with lefti <= j <= righti.

    Return an array answers, equal in length to queries, where answers[i] is the answer to the ith query. Since the answer to the ith query may be too large, each answers[i] should be returned modulo 109 + 7.

    Example 1:

    Input: n = 15, queries = [[0,1],[2,2],[0,3]]
    Output: [2,4,64]

    Explanation:
    For n = 15, powers = [1,2,4,8]. It can be shown that powers cannot be a smaller size.
    Answer to 1st query: powers[0] _ powers[1] = 1 _ 2 = 2.
    Answer to 2nd query: powers[2] = 4.
    Answer to 3rd query: powers[0] _ powers[1] _ powers[2] _ powers[3] = 1 _ 2 _ 4 _ 8 = 64.
    Each answer modulo 109 + 7 yields the same answer, so [2,4,64] is returned.

    Example 2:

    Input: n = 2, queries = [[0,0]]
    Output: [2]

    Explanation:
    For n = 2, powers = [2].
    The answer to the only query is powers[0] = 2. The answer modulo 109 + 7 is the same, so [2] is returned.

    Constraints:

    • 1 <= n <= 109
    • 1 <= queries.length <= 105
    • 0 <= starti <= endi < powers.length

    关键点在于 powers 实际就是 n 的二进制表达式过滤掉为 0 的位, 然后把每一位表达成一个 2 的 i 次方整数。 这一步解决了剩下的按部就班的计算每个查询的乘积就可以了


    
    impl Solution {
        pub fn product_queries(n: i32, queries: Vec<Vec<i32>>) -> Vec<i32> {
            let s = format!("{:b}", n);
            let l: Vec<usize> = s
                .chars()
                .rev()
                .enumerate()
                .filter(|&(_, c)| c == '1')
                .map(|(i, _)| i)
                .collect();
            queries
                .into_iter()
                .map(|q| {
                    l[q[0] as usize..=q[1] as usize]
                        .into_iter()
                        .fold(1, |mut p, &i| {
                            p *= 2i64.pow(i as u32);
                            p %= 1000000007i64;
                            p
                        }) as i32
                })
                .collect()
        }
    }
    
    
    • 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
  • 相关阅读:
    Spring(ioc)
    Spark On Yarn的两种运行模式
    如何上传自己的Jar到Maven中央仓库
    PMP_第2章章节试题
    行为设计模式之状态模式
    使用git将代码提交到Gitee
    CSS3病毒病原体图形特效
    cdh3.6.2集成flink1.12.0
    zookeeper节点数据类型介绍及集群搭建
    【C语言】【结构体的内存对齐】计算结构体内存大小,有图解
  • 原文地址:https://blog.csdn.net/wangjun861205/article/details/127774212