首页 > 其他分享 >[LeetCode] 1352. Product of the Last K Numbers 最后 K 个数的乘积

[LeetCode] 1352. Product of the Last K Numbers 最后 K 个数的乘积

时间:2023-09-14 13:00:12浏览次数:47  
标签:Product Last int 1352 getProduct add num prod data


Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream.

Implement the ProductOfNumbers class:

  • ProductOfNumbers() Initializes the object with an empty stream.
  • void add(int num) Appends the integer num to the stream.
  • int getProduct(int k) Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers.

The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.

Example:

Input
["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]
[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]

Output
[null,null,null,null,null,null,20,40,0,null,32]

Explanation
ProductOfNumbers productOfNumbers = new ProductOfNumbers();
productOfNumbers.add(3); // [3]
productOfNumbers.add(0); // [3,0]
productOfNumbers.add(2); // [3,0,2]
productOfNumbers.add(5); // [3,0,2,5]
productOfNumbers.add(4); // [3,0,2,5,4]
productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20
productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40
productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0
productOfNumbers.add(8); // [3,0,2,5,4,8]
productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32

Constraints:

  • 0 <= num <= 100
  • 1 <= k <= 4 * 104
  • At most 4 * 104 calls will be made to add and getProduct.
  • The product of the stream at any point in time will fit in a 32-bit integer.

这道题给了一个数据流,让返回最后k个数字的乘积,这里博主也尝试了最简单粗暴的解法,居然没有超时,可以通过。使用一个数组 data 来记录数据流,当调用 add 函数时,将数字加入 data 中。在 getProduct 函数中,遍历末尾k个数字,将它们乘起来返回即可,参见代码如下:


解法一:

class ProductOfNumbers {
public:
    ProductOfNumbers() {}
    
    void add(int num) {
        data.push_back(num);
    }
    
    int getProduct(int k) {
        int n = data.size(), res = 1;
        for (int i = 0; i < k; ++i) {
            res *= data[n - 1 - i];
        }
        return res;
    }

private:
    vector<int> data;
};

我们也可以在上面的解法上稍微做一些优化,这里的优化思路就是快速判断若数组末尾k个数字中有0存在的话,就马上返回0,而不用再计算k个数字的乘积。这里需要记录数组中所有0出现的位置,这里使用另外一个数组 zeros 来记录所有0的位置,在 add 函数中,判断若 num 为0,则用当前 data 数组的大小来当作0的位置,加入到 zeros 数组中,然后还是要将 num 加入到 data 中。在 getProduct 函数中,首先判断末尾k个数字中是否有0,最有可能出现在末尾k个数字中的0就是 zeros 数组中的最后一个位置,判断方法是用 zeros 数组的最后一个数组(若存在的话)和 n - k 相比较,若其大于等于 n - k,直接返回0。否则还是老老实实的将末尾k个数字相乘吧,参见代码如下:


解法二:

class ProductOfNumbers {
public:
    ProductOfNumbers() {}
    
    void add(int num) {
        if (num == 0) {
            zeros.push_back(data.size());
        }
        data.push_back(num);
    }
    
    int getProduct(int k) {
        int n = data.size(), res = 1;
        if (zeros.size() != 0 && zeros.back() >= n - k) return 0;
        for (int i = 0; i < k; ++i) {
            res *= data[n - 1 - i];
        }
        return res;
    }

private:
    vector<int> data, zeros;
};

再来看一种极大优化运行时间的解法,这里创建一个累加积数组 prod,其中 prod[i] 表示末尾 n-i 个数字的乘积,则末尾k个数字的乘积为 prod[n-k]。更新 prod 数组的方法是,每当进来一个数字 num 时,prod 数组新加一个1,然后对此时 prod 数组中每个数字都乘以 num,做个小优化,当 num 为1时,不需要乘,最后返回 prod[n-k] 即可,参见代码如下:


解法三:

class ProductOfNumbers {
 public:
     ProductOfNumbers() {}
    
     void add(int num) {
         prod.push_back(1);
         if (num == 1) return;
         for (int &a : prod) a *= num;
     }
    
     int getProduct(int k) {
         return prod[(int)prod.size() - k];
     }
    
 private:
     vector<int> prod;
 };

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1352


参考资料:

https://leetcode.com/problems/product-of-the-last-k-numbers/

https://leetcode.com/problems/product-of-the-last-k-numbers/solutions/510265/c-prefix-array/

https://leetcode.com/problems/product-of-the-last-k-numbers/solutions/510260/java-c-python-prefix-product/


LeetCode All in One 题目讲解汇总(持续更新中...)

标签:Product,Last,int,1352,getProduct,add,num,prod,data
From: https://www.cnblogs.com/grandyang/p/17702241.html

相关文章

  • python版elasticsearch入门笔记
    Elasticsearch是一个分布式、高扩展、高实时的搜索与数据分析引擎。Elasticsearch的实现原理主要分为以下几个步骤,首先用户将数据提交到Elasticsearch数据库中,再通过分词控制器去将对应的语句分词,将其权重和分词结果一并存入数据,当用户搜索数据时候,再根据权重将结果排名,打分,再......
  • elasticsearch
    Elasticsearch是一个基于Lucene(全文检索引擎工具)的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTfulweb接口。Elasticsearch是用Java语言开发的,并作为Apache许可条款下的开放源码发布,是一种流行的企业级搜索引擎。Elasticsearch用于云计算中,能够达到实时搜索......
  • 谈谈与Elasticsearch创始人Shay Banon面对面交流后的意外收获
    还记2017年11月,当时在阿里巴巴云栖大会上Elasticsearch与阿里云宣布达成战略合作,为中国市场提供崭新的用户体验。当时在现场听完Elasticsearch创始人ShayBanon的讲演受益匪浅,他在搜索的领域至今已经深耕了20多年,Elasticsearch第一个公开版本在2010年2月发布,2012年创建Elastic公司......
  • [题解]AT_arc116_b [ARC116B] Products of Min-Max
    思路我们容易可以得到一个朴素的做法,首先对\(a\)数组排序,然后枚举最大值和最小值\(a_i,a_j\),那么对于中间的元素都有选与不选两种情况,得到答案:\[\sum_{i=1}^{n}(a_i\timesa_i+(\sum_{j=i+1}^{n}a_i\timesa_j\times2^{j-i-1}))\]然后对这个式子做一个化简:......
  • ElasticSearch 8.6集群搭建过程​
    ElasticSearch8.6集群搭建过程一、系统信息操作系统版本:CentOSLinuxrelease8.4.2105elasticsearch版本:8.6.1机器信息:主机名ip地址CPU内存(G)数据盘es01192.168.205.251632/data/(500G)es02192.168.205.261632/data/(500G)es03192.168.205.271632/data/(500G)二、操作......
  • FELK学习(elastalertRule常用规则)
    FELK学习(elastalertRule常用规则) 发表于 2020-05-29 |  分类于 FELK这次着重看一看elastalert的配置及支持的Rule规则.对于一般的业务需求基本是可以满足的了.全局配置123456789101112131415161718es_host:127.0.0.1es_port:9200rules_folder:rulesrun_ev......
  • 开源ES管理工具ElasticView安装
    介绍ElasticView是一款用来监控ElasticSearch状态和操作ElasticSearch索引的web可视化工具。它由golang开发而成,具有部署方便,占用内存小等优点,官网地址:http://www.elastic-view.cnElasticSearch连接树管理(更方便的切换测试/生产环境)支持权限管理支持sql转换成dsl语法更......
  • 基于S3的elastic备份脚本
    下载插件并安装repository-s3下载对应es的版本的repository-s3插件,然后解压到ES软件目录的plugins目录下。elasticsearch.yml配置文件添加如下内容s3.client.default.endpoint:"S3地址:端口"s3.client.default.protocol:http使用脚本配置S3访问账号与密码,使ES可以连接S3......
  • ElasticSearch+Kibana on K8s 讲解与实战操作(版本7.17.3)
    目录一、概述二、ElasticSearch节点类型与作用三、K8s集群部署四、ElasticSearchonK8s开始部署1)下载安装包2)构建镜像3)修改yaml编排4)开始部署5)测试6)elasticsearch-head5)卸载五、Kibana编排部署1)下载安装包2)构建镜像3)修改yaml编排4)开始部署5)测试验证6)卸载六、Elasticsearch7......
  • 构建高性能全文搜索引擎:Java与Elasticsearch
    在今天的应用程序中,全文搜索功能变得越来越重要。无论是在线商店、博客网站还是企业应用,用户都希望快速而准确地找到他们需要的信息。Elasticsearch是一个强大的全文搜索引擎,可以轻松应对这一需求。本文将向你展示如何使用Java与Elasticsearch构建高性能的全文搜索引擎。什么是Elas......