国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

LeetCode //2675. Array of Objects to Matrix (Day 19 of LC JavaScript Challenge)

這篇具有很好參考價(jià)值的文章主要介紹了LeetCode //2675. Array of Objects to Matrix (Day 19 of LC JavaScript Challenge)。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

2675. Array of Objects to Matrix

Write a function that converts an array of objects arr into a matrix m.

arr is an array of objects or arrays. Each item in the array can be deeply nested with child arrays and child objects. It can also contain numbers, strings, booleans, and null values.

The first row m should be the column names. If there is no nesting, the column names are the unique keys within the objects. If there is nesting, the column names are the respective paths in the object separated by “.”.

Each of the remaining rows corresponds to an object in arr. Each value in the matrix corresponds to a value in an object. If a given object doesn’t contain a value for a given column, the cell should contain an empty string “”.

The colums in the matrix should be in lexographically ascending order.

?

Example 1:

Input:
arr = [
{“b”: 1, “a”: 2},
{“b”: 3, “a”: 4}
]
Output:
[
[“a”, “b”],
[2, 1],
[4, 3]
]
Explanation:
There are two unique column names in the two objects: “a” and “b”.
“a” corresponds with [2, 4].
“b” coresponds with [1, 3].

Example 2:

Input:
arr = [
{“a”: 1, “b”: 2},
{“c”: 3, “d”: 4},
{}
]
Output:
[
[“a”, “b”, “c”, “d”],
[1, 2, “”, “”],
[“”, “”, 3, 4],
[“”, “”, “”, “”]
]
Explanation:
There are 4 unique column names: “a”, “b”, “c”, “d”.
The first object has values associated with “a” and “b”.
The second object has values associated with “c” and “d”.
The third object has no keys, so it is just a row of empty strings.

Example 3:

Input:
arr = [
{“a”: {“b”: 1, “c”: 2}},
{“a”: {“b”: 3, “d”: 4}}
]
Output:
[
[“a.b”, “a.c”, “a.d”],
[1, 2, “”],
[3, “”, 4]
]
Explanation:
In this example, the objects are nested. The keys represent the full path to each value separated by periods.
There are three paths: “a.b”, “a.c”, “a.d”.

Example 4:

Input:
arr = [
[{“a”: null}],
[{“b”: true}],
[{“c”: “x”}]
]
Output:
[
[“0.a”, “0.b”, “0.c”],
[null, “”, “”],
[“”, true, “”],
[“”, “”, “x”]
]
Explanation:
Arrays are also considered objects with their keys being their indices.
Each array has one element so the keys are “0.a”, “0.b”, and “0.c”.

Example 5:

Input:
arr = [
{},
{},
{},
]
Output:
[
[],
[],
[],
[]
]
Explanation:
There are no keys so every row is an empty array.

Constraints:
  • 1 <= arr.length <= 1000
  • unique keys <= 1000

From: LeetCode
Link: 2675. Array of Objects to Matrix
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-455961.html


Solution:

Ideas:
The JavaScript function jsonToMatrix() aims to convert an array of JavaScript objects (possibly nested) into a 2-dimensional matrix. It uses depth-first search (DFS) to traverse the nested objects, creating a unique set of keys and a map for each object in the input array.
Here’s the step-by-step idea behind this function:
1. Initialize empty maps and key set: For each object in the input array, an empty map is created. These maps will store keys and corresponding values for each object. An empty set is also created to store unique keys.
2. Iterative DFS on each object: For each object in the array, an iterative DFS is performed. The DFS uses a stack to keep track of the current state. It starts with the entire object, pushes each key into the stack, and recursively pushes nested keys if a value is an object or array.
3. Populate maps and key set: In the DFS, each time it encounters a key-value pair, it adds the key to the current path (represented as curr.join(‘.’)), and if the value isn’t an object or array, it sets this path and corresponding value in the map of the current object (lookup.set(curr.join(‘.’), u[v])). It also adds this key to the set of unique keys (keys_set.add(k)).
4. Construct the matrix: After populating the maps and key set, it constructs the matrix. The first row is filled with the sorted unique keys. For each subsequent row corresponding to an object, it checks if the object has a value for each key (column) and adds it to the row, or adds an empty string if there’s no value.
In this way, the function transforms an array of possibly nested objects into a matrix, where each row corresponds to an object, each column corresponds to a unique key, and each cell contains the value of the corresponding key for the corresponding object, or an empty string if the key doesn’t exist in the object. The keys are sorted in lexicographic order.
Note: The time complexity is O(l * mlogm + m * n) and the space complexity is O(l * m + m * n), where l is the maximum depth of the nested objects, m is the number of unique keys, and n is the number of objects in the array.
Code:
/**
 * @param {Array} arr
 * @return {Matrix}
 */
var jsonToMatrix = function(arr) {
    let row = new Array(arr.length).fill(null).map(() => new Map());  
    let keys_set = new Set();  
    arr.forEach((x, i) => {
        const iter_dfs = (u, lookup) => {  
            let stk = [[1, u, undefined]];  
            let curr = []  
            while (stk.length) {  
                const [step, u, v] = stk.pop();  
                if (step === 1) {  
                    for (const v in u) {  
                        stk.push([3, u, v]);  
                        stk.push([2, u, v]);  
                    }  
                } else if (step === 2) {  
                    curr.push(v);  
                    if (!(u[v] !== null && (typeof u[v] === 'object' || Array.isArray(u[v])))) {  
                        lookup.set(curr.join('.'), u[v]);  
                    } else {  
                        stk.push([1, u[v], null])  
                    }  
                } else if (step === 3) {  
                    curr.pop(); 
                }
            }
        }
        iter_dfs(x, row[i]); 
        for (const [k, _] of row[i].entries()) {  
            keys_set.add(k);
        }
    });  
    let result = [Array.from(keys_set).sort()];  
    for (let i = 0; i < row.length; ++i) {  
        result.push([])
        for (let j = 0; j < result[0].length; ++j) {  
            result[i+1].push(row[i].has(result[0][j]) ? row[i].get(result[0][j]) : '');
        }
    }
    return result
};

到了這里,關(guān)于LeetCode //2675. Array of Objects to Matrix (Day 19 of LC JavaScript Challenge)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • numpy 鄰接矩陣轉(zhuǎn)稀疏矩陣 array to scipy csr_matrix

    也就是說(shuō),一個(gè)dense的numpy矩陣,如何轉(zhuǎn)換成scipy包里面的sparse的csr矩陣看代碼: 輸出: print(csr_a.toarray()) print(csr_a.tocoo())

    2024年02月12日
    瀏覽(23)
  • LeetCode --- 1929. Concatenation of Array 解題報(bào)告

    Given an integer array? nums ?of length? n , you want to create an array? ans ?of length? 2n ?where? ans[i] == nums[i] ?and? ans[i + n] == nums[i] ?for? 0 = i n ?( 0-indexed ). Specifically,? ans ?is the? concatenation ?of two? nums ?arrays. Return? the array? ans . Example 1: Example 2:

    2024年02月09日
    瀏覽(25)
  • LeetCode 2475. Number of Unequal Triplets in Array【數(shù)組,排序,哈希表】簡(jiǎn)單

    本文屬于「征服LeetCode」系列文章之一,這一系列正式開始于2021/08/12。由于LeetCode上部分題目有鎖,本系列將至少持續(xù)到刷完所有無(wú)鎖題之日為止;由于LeetCode還在不斷地創(chuàng)建新題,本系列的終止日期可能是永遠(yuǎn)。在這一系列刷題文章中,我不僅會(huì)講解多種解題思路及其優(yōu)化,

    2024年02月09日
    瀏覽(22)
  • LeetCode 2496. Maximum Value of a String in an Array【字符串,數(shù)組】簡(jiǎn)單

    本文屬于「征服LeetCode」系列文章之一,這一系列正式開始于2021/08/12。由于LeetCode上部分題目有鎖,本系列將至少持續(xù)到刷完所有無(wú)鎖題之日為止;由于LeetCode還在不斷地創(chuàng)建新題,本系列的終止日期可能是永遠(yuǎn)。在這一系列刷題文章中,我不僅會(huì)講解多種解題思路及其優(yōu)化,

    2024年02月11日
    瀏覽(17)
  • day19【LeetCode力扣】160.相交鏈表

    day19【LeetCode力扣】160.相交鏈表

    1.題目描述 給你兩個(gè)單鏈表的頭節(jié)點(diǎn) headA 和 headB ,請(qǐng)你找出并返回兩個(gè)單鏈表相交的起始節(jié)點(diǎn)。如果兩個(gè)鏈表不存在相交節(jié)點(diǎn),返回 null 。 圖示兩個(gè)鏈表在節(jié)點(diǎn) c1 開始相交**:** 題目數(shù)據(jù) 保證 整個(gè)鏈?zhǔn)浇Y(jié)構(gòu)中不存在環(huán)。 注意 ,函數(shù)返回結(jié)果后,鏈表必須 保持其原始結(jié)構(gòu)

    2024年01月18日
    瀏覽(42)
  • 力扣python刷題day04|LeetCode24、19、160、142

    力扣python刷題day04|LeetCode24、19、160、142

    題目 來(lái)源:24:兩兩交換鏈表中的節(jié)點(diǎn) 建議使用虛擬頭結(jié)點(diǎn),這樣會(huì)方便很多,要不然每次針對(duì)頭結(jié)點(diǎn)(沒(méi)有前一個(gè)指針指向頭結(jié)點(diǎn)),還要單獨(dú)處理。 接下來(lái)就是交換相鄰兩個(gè)元素了,此時(shí)一定要畫圖,不畫圖,操作多個(gè)指針很容易亂,而且要操作的先后順序 方法: 題目

    2024年02月16日
    瀏覽(19)
  • LeetCode //C - 19. Remove Nth Node From End of List

    LeetCode //C - 19. Remove Nth Node From End of List

    Given the head of a linked list, remove the n t h n^{th} n t h node from the end of the list and return its head. ? Example 1: Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5] Example 2: Input: head = [1], n = 1 Output: [] Example 3: Input: head = [1,2], n = 1 Output: [1] Constraints: The number of nodes in the list is sz. 1 = sz = 30 0 = Node.val = 100 1

    2024年02月10日
    瀏覽(23)
  • LeetCode2111. Minimum Operations to Make the Array K-Increasing——?jiǎng)討B(tài)規(guī)劃

    You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k. The array arr is called K-increasing if arr[i-k] = arr[i] holds for every index i, where k = i = n-1. For example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because: arr[0] = arr[2] (4 = 5) arr[1] = arr[3] (1 = 2) arr[2] = arr[4] (5 = 6) arr[3] = arr[5]

    2024年03月09日
    瀏覽(22)
  • 【每日一題】Leetcode - 19. Remove Nth Node From End of List

    【每日一題】Leetcode - 19. Remove Nth Node From End of List

    Leetcode - 19. Remove Nth Node From End of List Drawing on the method of finding midpoints in linked lists, use quick slow pointer Finding midpoints in linked lists nothing

    2024年02月12日
    瀏覽(22)
  • 【LeetCode 算法】Minimum Operations to Halve Array Sum 將數(shù)組和減半的最少操作次數(shù)-Greedy

    給你一個(gè)正整數(shù)數(shù)組 nums 。每一次操作中,你可以從 nums 中選擇 任意 一個(gè)數(shù)并將它 減小 到 恰好 一半 。(注意,在后續(xù)操作中你可以對(duì)減半過(guò)的數(shù)繼續(xù)執(zhí)行操作) 請(qǐng)你返回將 nums 數(shù)組和 至少 減少一半 的 最少 操作數(shù)。 1 = n u m s . l e n g t h = 1 0 5 1 = n u m s [ i ] = 1 0 7 1 = num

    2024年02月15日
    瀏覽(22)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包