当前位置: 面试刷题>> 内积 (经典算法题500道)


首先,我会补充完整题目描述,然后分别给出PHP、Python、JavaScript的示例代码来解决这个问题。题目可能是这样的:

题目描述: 给定两个等长整数数组AB,请计算它们的内积(点积)。内积的定义是:两个等长向量AB的内积等于它们对应元素乘积的和,即A[0]*B[0] + A[1]*B[1] + ... + A[n-1]*B[n-1],其中n是数组AB的长度。

PHP 示例代码

function dotProduct($A, $B) {
    $n = count($A);
    if ($n != count($B)) {
        throw new Exception("Arrays are not of equal length.");
    }
    $result = 0;
    for ($i = 0; $i < $n; $i++) {
        $result += $A[$i] * $B[$i];
    }
    return $result;
}

// 示例
$A = [1, 2, 3];
$B = [4, 5, 6];
echo dotProduct($A, $B); // 输出 32

Python 示例代码

def dot_product(A, B):
    if len(A) != len(B):
        raise ValueError("Arrays are not of equal length.")
    return sum(a * b for a, b in zip(A, B))

# 示例
A = [1, 2, 3]
B = [4, 5, 6]
print(dot_product(A, B))  # 输出 32

JavaScript 示例代码

function dotProduct(A, B) {
    if (A.length !== B.length) {
        throw new Error("Arrays are not of equal length.");
    }
    let result = 0;
    for (let i = 0; i < A.length; i++) {
        result += A[i] * B[i];
    }
    return result;
}

// 示例
const A = [1, 2, 3];
const B = [4, 5, 6];
console.log(dotProduct(A, B)); // 输出 32

码小课:在码小课网站上,你可以找到更多关于算法和数据结构的知识分享,包括但不限于数组操作、函数式编程、面向对象编程等高级概念。通过不断学习和实践,你可以提升自己的编程技能,解决更多复杂的问题。

推荐面试题