HoneyMoose
  • 首页
  • Java
  • Jersey
  • Jira
  • Confluence
  • U.S.
    • USRealEstate
    • USVisaTrack
    • H1B
  • 项目和网站
    • CWIKI.US
    • OSSEZ 社区
    • WIKI.OSSEZ.COM
    • BUG.OSSEZ.COM
    • RSS.OSSEZ.COM
BLOG.OSSEZ.COM
A responsive blog theme focused om user reading experience
  1. Home
  2. Computer Science
  3. Algorithm(算法)
  4. This article

[LintCode] Dot Product(点积)

2018年12月14日 845Browse 0Like 0Comments

描述

给出两个数组,求它们的点积。(Wikipedia)

 

如果没有点积则返回-1

样例

Input:A = [1,1,1]
B = [2,2,2]
Output:6

代码

请单击下面链接在 GitHub 上查看最新的源代码:

https://github.com/cwiki-us/java-tutorial/blob/master/src/test/java/com/ossez/lang/tutorial/tests/lintcode/LintCode1480DotProductTest.java

package com.ossez.lang.tutorial.tests.lintcode;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * 1480
 * <ul>
 * <li>@see
 * <a href= "https://www.cwiki.us/display/ITCLASSIFICATION/Dot+Product">https://www.cwiki.us/display/ITCLASSIFICATION/Dot+Product</a>
 * <li>@see<a href= "https://www.lintcode.com/problem/dot-product/">https://www.lintcode.com/problem/dot-product/</a>
 * </ul>
 * </p>
 * 
 * @author YuCheng
 *
 */
public class LintCode1480DotProductTest {

  private final static Logger logger = LoggerFactory.getLogger(LintCode1480DotProductTest.class);

  /**
   * 
   */
  @Test
  public void testMain() {
    logger.debug("BEGIN");
    int[] A = { 1, 1, -1 };
    int[] B = { 2147483647, 1, 3 };

    int retStatus = 0;

    // LENGTH CHECK
    if (A.length == 0 || B.length == 0 || A.length != B.length)
      retStatus = -1;

    // ADDED
    if (retStatus != -1) {
      for (int i = 0; i < A.length; i++) {
        retStatus = retStatus + A[i] * B[i];
      }
    }

    System.out.println(retStatus);
  }

}

 

点评

这个问题的关键是要了解点积是如何进行计算的。

对输入的数组还需要进行 NULL 的校验和计算。

摘录点积的计算方法如下:

向量是由n个实数组成的一个n行1列(n*1)或一个1行n列(1*n)的有序数组;

向量的点乘,也叫向量的内积、数量积,对两个向量执行点乘运算,就是对这两个向量对应位一一相乘之后求和的操作,点乘的结果是一个标量。

点乘公式

对于向量 a 和向量 b:

a和b的点积公式为:

 

 

要求一维向量 a 和向量 b 的行列数相同。

因为要求向量 a 和 b 的行列数相同,因此在程序中需要先进行判断才可以。

Tags: LintCode 算法
Last updated:2018年12月15日

Kratos

stay absorbed stay excellent

Like
< Previous
Next >

Comments

Cancel reply

Newest Hotspots Random
Newest Hotspots Random
IntelliJ IDEA 2023.1 版本添加了包中类的列表功能 Jenkins 修改启动的端口 Spring 项目运行提示错误 Not a managed type Linux 查看 SELinux 的状态 WordPress 网站 Error Establishing a Database Connection(建立数据库连接时出错) Linux 开启或关闭 SELinux
上 JAVA 直播课老师如何将自己的编程环境共享给学生 在 Confluence 6 中连 Jira 的问题解决 Spring Boot 2.4 部署你的第一个 Spring Boot 应用需要的环境 配置一个 Confluence 6 环境 电脑软件(例如 Adobe、Autodesk)为什么那么容易被破解 说说这 48 小时核酸检测的时间
Categories
  • Algorithm(算法)
  • AMQP
  • Angular
  • CI
  • Compile And CI
  • Computer Science
  • Confluence
  • DataBase
  • Gradle
  • H1B
  • Hibernate
  • IDE
  • Java
  • Jersey
  • Jira
  • MariaDB
  • PrestaShop
  • Spring
  • Spring Batch
  • U.S.
  • USRealEstate
  • USVisaTrack
  • 我的小厨

COPYRIGHT © 2020 HoneyMoose. ALL RIGHTS RESERVED.

THEME CWIKIUS.CN MADE BY VTROIS