【C++】【LeetCode数组】1570. 两个稀疏向量的点积

该文章介绍了一个C++实现,用于计算两个稀疏向量的点积。它通过遍历每个向量的元素并进行乘法运算来得到结果。SparseVector类包含一个构造函数和一个dotProduct方法,后者返回两个向量的点积。
摘要由CSDN通过智能技术生成


题目链接

https://leetcode.cn/problems/dot-product-of-two-sparse-vectors/

考察知识点

Vector的遍历

解题思路

在类中声明一个成员变量,vector

在dotProduct方法中,获取形参SparseVector &tec中的vector,两个vector的长度一定是一样的,获取其中某一个vector的长度,遍历,计算点积。

代码

class SparseVector {
public:
    
    SparseVector(vector<int> &nums) {
        this->v = nums;
    }

    // Return the dotProduct of two sparse vectors
    int dotProduct(SparseVector& vec) {
        int res = 0;
        vector<int> temp = vec.v;
        for (int i = 0; i < this->v.size(); ++i) {
            res += (this->v[i] * temp[i]);
        }
        return res;
    }
    
private:
    vector<int> v;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值