LeetCode //2722. Join Two Arrays by ID (Day 30 of LC JavaScript Challenage)

这篇具有很好参考价值的文章主要介绍了LeetCode //2722. Join Two Arrays by ID (Day 30 of LC JavaScript Challenage)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

2722. Join Two Arrays by ID

Given two arrays arr1 and arr2, return a new array joinedArray. All the objects in each of the two inputs arrays will contain an id field that has an integer value. joinedArray is an array formed by merging arr1 and arr2 based on their id key. The length of joinedArray should be the length of unique values of id. The returned array should be sorted in ascending order based on the id key.

If a given id exists in one array but not the other, the single object with that id should be included in the result array without modification.

If two objects share an id, their properties should be merged into a single object:

  • If a key only exists in one object, that single key-value pair should be included in the object.

  • If a key is included in both objects, the value in the object from arr2 should override the value from arr1.

 

Example 1:

Input:
arr1 = [
{“id”: 1, “x”: 1},
{“id”: 2, “x”: 9}
],
arr2 = [
{“id”: 3, “x”: 5}
]
Output:
[
{“id”: 1, “x”: 1},
{“id”: 2, “x”: 9},
{“id”: 3, “x”: 5}
]
Explanation: There are no duplicate ids so arr1 is simply concatenated with arr2.

Example 2:

Input:
arr1 = [
{“id”: 1, “x”: 2, “y”: 3},
{“id”: 2, “x”: 3, “y”: 6}
],
arr2 = [
{“id”: 2, “x”: 10, “y”: 20},
{“id”: 3, “x”: 0, “y”: 0}
]
Output:
[
{“id”: 1, “x”: 2, “y”: 3},
{“id”: 2, “x”: 10, “y”: 20},
{“id”: 3, “x”: 0, “y”: 0}
]
Explanation: The two objects with id=1 and id=3 are included in the result array without modifiction. The two objects with id=2 are merged together. The keys from arr2 override the values in arr1.

Example 3:

Input:
arr1 = [
{“id”: 1, “b”: {“b”: 94},“v”: [4, 3], “y”: 48}
]
arr2 = [
{“id”: 1, “b”: {“c”: 84}, “v”: [1, 3]}
]
Output: [
{“id”: 1, “b”: {“c”: 84}, “v”: [1, 3], “y”: 48}
]
Explanation: The two objects with id=1 are merged together. For the keys “b” and “v” the values from arr2 are used. Since the key “y” only exists in arr1, that value is taken form arr1.

Constraints:
  • arr1 and arr2 are valid JSON arrays
  • Each object in arr1 and arr2 has a unique integer id key
  • 2 < = J S O N . s t r i n g i f y ( a r r 1 ) . l e n g t h < = 1 0 6 2 <= JSON.stringify(arr1).length <= 10^6 2<=JSON.stringify(arr1).length<=106
  • 2 < = J S O N . s t r i n g i f y ( a r r 2 ) . l e n g t h < = 1 0 6 2 <= JSON.stringify(arr2).length <= 10^6 2<=JSON.stringify(arr2).length<=106

From: LeetCode
Link: 2722. Join Two Arrays by ID
文章来源地址https://www.toymoban.com/news/detail-513158.html


Solution:

Ideas:
This code first creates a Map object to store the objects in arr1 and arr2, keyed by their id. Then, it iterates through arr2 and merges each object with the existing object in the Map with the same id. If no object exists in the Map with the same id, the object is simply added to the Map. Finally, the Map is converted to an array and sorted by id. The sorted array is then returned.
Code:
/**
 * @param {Array} arr1
 * @param {Array} arr2
 * @return {Array}
 */
var join = function(arr1, arr2) {
    const idMap = new Map();
    for (const obj of arr1) {
        idMap.set(obj.id, obj);
    }
    for (const obj of arr2) {
        const existingObj = idMap.get(obj.id);
        if (existingObj) {
            const mergedObj = {...existingObj, ...obj};
            idMap.set(obj.id, mergedObj);
        } else {
            idMap.set(obj.id, obj);
        }
    }
    const joinedArray = [...idMap.values()];
    joinedArray.sort((a, b) => a.id - b.id);
    return joinedArray;
};

到了这里,关于LeetCode //2722. Join Two Arrays by ID (Day 30 of LC JavaScript Challenage)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • LeetCode //C - 4. Median of Two Sorted Arrays

    Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)) .   Example 1: Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2. Example 2: Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanati

    2024年02月06日
    浏览(40)
  • LeetCode 1385. Find the Distance Value Between Two Arrays

    Given two integer arrays  arr1  and  arr2 , and the integer  d ,  return the distance value between the two arrays . The distance value is defined as the number of elements  arr1[i]  such that there is not any element  arr2[j]  where  |arr1[i]-arr2[j]| = d . Example 1: Example 2: Example 3: Constraints: 1 = arr1.length, arr2.length = 500 -1000 = ar

    2024年02月10日
    浏览(41)
  • LeetCode --- 1880. Check if Word Equals Summation of Two Words 解题报告

    The  letter value  of a letter is its position in the alphabet  starting from 0  (i.e.  \\\'a\\\' - 0 ,  \\\'b\\\' - 1 ,  \\\'c\\\' - 2 , etc.). The  numerical value  of some string of lowercase English letters  s  is the  concatenation  of the  letter values  of each letter in  s , which is then  converted  into an integer. For example, if  s = \\\"acb\\\" , we

    2024年02月13日
    浏览(42)
  • 算法练习Day30 (Leetcode/Python-动态规划)

    62. Unique Paths There is a robot on an  m x n  grid. The robot is initially located at the  top-left corner  (i.e.,  grid[0][0] ). The robot tries to move to the  bottom-right corner  (i.e.,  grid[m - 1][n - 1] ). The robot can only move either down or right at any point in time. Given the two integers  m  and  n , return  the number of possible

    2024年01月20日
    浏览(41)
  • Java中合并两个数组的4种方法(How to Merge Two Arrays in Java)

    int[] arr1={1, 2, 3, 4, 5, 6}; //first array int[] arr2={7, 8, 9, 0}; //second array int[] arr3={1, 2, 3, 4, 5, 6, 7, 8, 9, 0} //resultant array There are following ways to merge two arrays: 1.Java arraycopy() method 2.Without using arraycopy() method 3.Java Collections 4.Java Stream API Java arraycopy() is the method of System class which belongs to java.la

    2024年02月11日
    浏览(41)
  • LeetCode 1. Two Sum 两数之和

    题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2

    2023年04月25日
    浏览(41)
  • TWO DAY | WEB安全之OWASP TOP10漏洞

    TWO DAY | WEB安全之OWASP TOP10漏洞 OWASP:开放式Web应用程序安全项目(Open Web Application Security Project),OWASP是一家国际性组织机构,并且是一个开放的、非盈利组织,它致力于协助政府、企业开发、升级各类应用程序以保证其可信任性。所有OWASP的工具、文档、研讨以及所有分会都对

    2024年02月12日
    浏览(40)
  • Hive:聚合函数、GROUP BY、ORDER BY、LIMIT、执行顺序和JOIN、函数

    1.聚合函数 常见的聚合函数: Count、Sum、Max、Min和Avg 特点:不管原始数据多少条,聚合之后只有一条 Count(column)返回某列的行数,不包括NULL值 2.GROUP BY select中的字段要么是GROUP BY字段,要么是被聚合函数应用的字段 2.HAVING WHERE中无法出现聚合函数,所以有了HAVING WHERE是分组前

    2024年02月07日
    浏览(46)
  • spark 的group by ,join数据倾斜调优

    spark任务中最常见的耗时原因就是数据分布不均匀,从而导致有些task运行时间很长,长尾效应导致的整个job运行耗时很长 首先我们要定位数据倾斜,我们可以通过在spark ui界面中查看某个stage下的task的耗时,如果发现某些task耗时很长,对应要处理的数据很多,证明有数据倾斜

    2024年02月21日
    浏览(44)
  • 已解决ValueError: All arrays must be of the same length

    已解决(pandas创建DataFrame对象报错)ValueError: All arrays must be of the same length 粉丝群里面的一个粉丝用pandas创建DataFrame对象,但是发生了报错(跑来找我求助,然后顺利帮助他解决了,顺便记录一下希望可以帮助到更多遇到这个bug不会解决的小伙伴),报错信息和代码如下: 报

    2024年02月02日
    浏览(50)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包