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奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/4999777.html,如需转载请自行联系原作者