[英]Javascript: Concise way to fill sparse array with object
我正在使用一個數組來存儲對象(節點之間的有向邊),並且想使用一個數組來存儲對象,這樣我就可以使用數組的索引來引用 object id。
/**
* Take a graph where
* @param {number} N: The number of Nodes of in the graph
* @param {number[][]} trust: an array of directed edges trust [[a,b]] draws 'a trusts b'
* @return {number}
*/
var findJudge = function(N, trust) {
let nodes = [
{
trusts: {},
trustedBy: {}
}
]
trust.forEach(pair => {
nodes[pair[0]].trusts = pair[1]
nodes[pair[1]].trusted = pair[0]
})
return -1
};
示例輸入: N = 2
和trust = [[1,2]]
錯誤,因為nodes[2]
在運行時還不存在。
如果可能的話,我想避免用 null 值預先填充數組,以防 N 是一個非常大的數字。 也許這不是填充稀疏鄰接表的正確數據結構。 有沒有辦法說var x = new Array(of type object, of length N)
?
我對任何和所有解決方案持開放態度。
編輯以顯示問題https://leetcode.com/problems/find-the-town-judge/description/的上下文
如果可能的話,我想避免用 null 值預先填充數組,以防 N 是一個非常大的數字。
您可以通過首先檢查trust
參數的大小來避免這種極端情況。 如果有解決方案,那么至少trust.length >= N-1
。
但是,如果該測試通過,那么您無論如何都需要查看所有trust
條目,以確定是否有法官,以及法官是誰。 因此,如果您還創建所有 N 個節點,甚至在迭代trust
之前,它不會增加工作的時間復雜度。
其次,您的代碼當前會覆蓋信息,因此每個節點只能存儲一個受信任的人和一個受信任的人。 您真正需要的是trusted
和trustedBy
可以存儲多個條目; 至少當你想制作一個雙線程圖時。
但是當你真正考慮它時,如果你只知道一個節點的trusted
數量和trustedBy
的數量,你就會得到足夠的信息。 法官必須是trusted
計數為零且trustedBy
計數為N-1 的人。 不可能有兩個,因為那將是一個矛盾。
因此,您可以避免創建圖表。 只存儲從 0 開始的計數就足夠了。
就像在 JavaScript 數組索引從零開始而不是 1 一樣,您的nodes
數組的索引將比trust
數組中使用的實際人員 ID 小一。
以下是該代碼的外觀:
var findJudge = function(N, trust) { // Quick exit, to avoid unnecessary looping if (trust.length < N - 1) return -1; // Create all nodes (with index one less -- starting at 0) let nodes = Array.from({ length: N }, () => ({ trusts: 0, trustedBy: 0 })); // Count trust relationships in both directions trust.forEach(([trustedBy, trusted]) => { nodes[trustedBy - 1].trusts++; nodes[trusted - 1].trustedBy++; }); // The only judge meets the following requirements // Add one to the found judge to go from 0-based to 1-based. return nodes.findIndex(node => node.trusts == 0 && node.trustedBy == N - 1) + 1 || -1; }; console.log(findJudge(3, [[1,2],[3,2],[1,3]]));
如果您關心速度,則將所有循環替換為舊式for
循環,而不是對象數組 ( trust
),使用兩個簡單的計數 arrays ( trusts
和trustedBy
),因為 arrays 整數通常會導致更好的執行時間比 arrays 的對象。
根據@Bergi 的建議,我只需檢查 object 是否存在並創建它。 如果有人有任何其他 javascript 魔法,仍然對其他建議感到好奇
var findJudge = function(N, trust) {
function node() {
trusts: {}
trustedBy: {}
}
let nodes = []
trust.forEach(pair => {
pair.forEach(element => {
if (nodes[element] === undefined)
nodes[element] = new node()
})
nodes[pair[0]].trusts = pair[1]
nodes[pair[1]].trusted = pair[0]
})
return -1
};
會將此作為評論發布,但評論不允許代碼塊格式化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.