LintCode: Cosine Similarity
C++
1 class Solution { 2 public: 3 /** 4 * @param A: An integer array. 5 * @param B: An integer array. 6 * @return: Cosine similarity. 7 */ 8 double cosineSimilarity(vector<int> A, vector<int> B) { 9 // write your code here 10 int AB = 0, size; 11 double lenA = 0, lenB = 0; 12 size = A.size(); 13 for (int i = 0; i < size; i++) { 14 AB += A[i]*B[i]; 15 lenA += A[i]*A[i]; 16 lenB += B[i]*B[i]; 17 } 18 if (0 == AB && 0 == lenA && 0 == lenB) { 19 return 2; 20 } else { 21 return AB/(sqrt(lenA)*sqrt(lenB)); 22 } 23 24 } 25 };
找我内推: 字节跳动各种岗位
作者:
ZH奶酪(张贺)
邮箱:
cheesezh@qq.com
出处:
http://www.cnblogs.com/CheeseZH/
*
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。