簡體   English   中英

JavaScript中時間復雜度為O(n)的好友推薦算法

[英]Friends recommendation algorithm with O(n) time complexity in JavaScript

const data = [
  {
    name: 'Bob',
    friends: ['Alice', 'Eve', 'Charlie']
  },
  {
    name: 'Alice',
    friends: ['Bob', 'Dan']
  },
  {
    name: 'Dan',
    friends: ['Alice', 'Eve']
  },
  {
    name: 'Charlie',
    friends: ['Bob']
  }
];

function get_top_k_recommended_friends(name, cutoff) {

}

get_top_k_recommended_friends('Alice', 2) // [Eve, Charlie]
get_top_k_recommended_friends('Alice', 1) // [Eve]

這個 function 接受兩個整數(user_id,cutoff_k)並向這個特定的 user_id 提供新朋友的推薦(表示為整數列表)。 推薦朋友的定義如下:

A recommended friend is a friend who has mutual friends with the original user_id’s friends. 

For example, assume Alice is friends with Bob and Bob is friends with Eve but Alice is not friends with Eve. So when you call get_recommended_friends(Alice), you get Eve. You also get Alice if you call get_recommended_friends(Eve). 

If Bob also is friends with Charlie but Alice is not friends with Charlie, then calling get_recommended_friends(Alice) should yield [Eve, Charlie].

編寫 get_recommended_friends 的兩個重要要求是

  1. 返回的推薦好友列表必須按照他們與請求用戶的最多共同好友數量排序
  2. 他們應該只返回前 k 個推薦的朋友(k 是一個截止)

根據提供的數據調用 get_top_k_recommended_friends(Alice, 2) 應該產生 [Eve, Charlie] 其中 Eve 在 Charlie 之前被訂購,因為 Eve 是 Alice 的兩個朋友(Bob 和 Dan)的朋友,而 Charlie 只是 Alice 的一個朋友的朋友(鮑勃)。 get_top_k_recommended_friends(Alice, 1) 將產生 [Eve]。

圖上與根(原始用戶)的距離為 2 並且連接到至少一個距離為 1 的節點的節點應該是共同的朋友。

(例如 Eve 和 Charlie 與 Alice 的距離為 2,並且都與距離為 1 的節點相連(Bob 和 Dan))

因此,對於距離為 2 ( f2 ) 的每個朋友,您可以計算它連接到的距離為 1 的節點的數量 ( mutual_count )。

get_top_k_recommended_friends(user, cutoff)
  for f1 in friends[user]:
    for f2 in friends[f1] - friends[user]: // friends of f1 but not of user
      for f3 in friends[f2]: // check each edge(f2, f3)
        if edge(f2, f3) not visited && f3 != f1 && f3 in friends[user]: 
          // f2 is a mutual friend of f1 and f3
          // f1 and f3 are both friends of user, so f2 is a recommended friend
          mutual_count[f2] += 1
          mark edge(f2, f3) and edge(f3, f2) as visited

  return k_largest(mutual_count, cutoff)

檢查集合中是否存在元素可以在 O(1) 中完成。 該算法只會訪問距離根(及其邊緣)距離為 1 和 2 的朋友,因此return k_largest(mutual_count, cutoff)之前的所有內容都應該是 O(n+m),其中 n 和 m 是上述節點的數量,並且邊緣,分別。

對於k_largest ,可以使用quickselect算法找到第 k 個最大值,然后過濾掉並排序 k 個最大值,其平均復雜度應該是復雜度 O(n + k log k)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM