首页 > 其他 > 详细

445 余弦相似度

时间:2018-06-27 16:03:11      阅读:239      评论:0      收藏:0      [点我收藏+]

原题网址:https://www.lintcode.com/problem/cosine-similarity/description

描述

Cosine similarity is a measure of similarity between two vectors of an inner product space that measures the cosine of the angle between them. The cosine of 0° is 1, and it is less than 1 for any other angle.

See wiki: Cosine Similarity

Here is the formula:

技术分享图片

Given two vectors A and B with the same size, calculate the cosine similarity.

Return 2.0000 if cosine similarity is invalid (for example A = [0] and B = [0]).

您在真实的面试中是否遇到过这个题?  

样例

给出 A = [1, 2, 3]B = [2, 3 ,4].

返回 0.9926.

给出 A = [0]B = [0].

返回 2.0000

 

思路:直接按照公式计算就好。注意余弦相似度无效的情况,分母等于0或者空数组。

PS:一开始提交的代码没考虑到空数组以及数组全0的情况,只排除了样例中的无效情况……汗

AC代码:

class Solution {
public:
    /*
     * @param A: An integer array
     * @param B: An integer array
     * @return: Cosine similarity
     */
    double cosineSimilarity(vector<int> &A, vector<int> &B) {
        // write your code here
    int n=A.size();
    if (n==0)
    {
        return 2.0;
    }
    double x=0.0,sumA=0.0,sumB=0.0;
    for (int i=0;i<n;i++)
    {
        x=x+A[i]*B[i];
        sumA=sumA+A[i]*A[i];
        sumB=sumB+B[i]*B[i];
    }
    sumA=sqrt(sumA);
    sumB=sqrt(sumB);
    if (sumA==0||sumB==0)
    {
        return 2.0;
    }
    double result=x/(sumA*sumB);
    return result;
    
    }
};

 

 

445 余弦相似度

原文:https://www.cnblogs.com/Tang-tangt/p/9234436.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!