445 余弦相似度
原题网址: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;
}
};
其他参考:
https://blog.csdn.net/zhaohuiyan9837/article/details/78472537