We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
原题链接: https://leetcode.cn/problems/merge-similar-items/
解题思路:
i
j
items1[i][0] === items2[j][0]
items1[i][0] < items2[j][0]
items1[i]
items1[i][0] > items2[j][0]
items2[j]
/** * @param {number[][]} items1 * @param {number[][]} items2 * @return {number[][]} */ var mergeSimilarItems = function (items1, items2) { let result = [] // 先对两个数组进行排序 items1.sort((a, b) => a[0] - b[0]) items2.sort((a, b) => a[0] - b[0]) // 用两个指针分别合并数组 for (let i = 0, j = 0; i < items1.length || j < items2.length; ) { // 价值相同时,需要将两个重量相加 if (items1[i]?.[0] === items2[j]?.[0]) { result.push([items1[i][0], items1[i++][1] + items2[j++][1]]) } // 如果指针j已经移出items2,或者items1[i]的价值比items2[j]小,此时直接存储items1[i] else if (!items2[j] || items1[i]?.[0] < items2[j]?.[0]) { result.push(items1[i++]) } // 如果指针已经移出items1,或者items1[i]的价值比items2[j]大,此时直接存储items2[j] else if (!items1[i] || items1[i]?.[0] > items2[j]?.[0]) { result.push(items2[j++]) } } return result }
复杂度分析:
O(n+m)log(n+m)
The text was updated successfully, but these errors were encountered:
No branches or pull requests
原题链接:
https://leetcode.cn/problems/merge-similar-items/
解题思路:
i
和j
分别遍历两个数组的元素items1[i][0] === items2[j][0]
,就将两个同价值的物品重量相加items1[i][0] < items2[j][0]
,就存储items1[i]
items1[i][0] > items2[j][0]
,就存储items2[j]
复杂度分析:
O(n+m)log(n+m)
The text was updated successfully, but these errors were encountered: