1. 程式人生 > >445 余弦相似度

445 余弦相似度

urn invalid SM 分享圖片 ++ SQ tor 遇到 similar

原題網址: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 余弦相似度