LeetCode: Finding Pairs With A Certain Sum Solution
1/**2 * @param {number[]} nums13 * @param {number[]} nums24 */5var FindSumPairs = function (nums1, nums2) {6 this.nums1 = nums17 this.nums2 = nums28 this.occurences2 = nums2.reduce(9 (acc, el) => acc.set(el, (acc.get(el) || 0) + 1),10 new Map()11 )12}1314/**15 * @param {number} index16 * @param {number} val17 * @return {void}18 */19FindSumPairs.prototype.add = function (index, val) {20 const num = this.nums2[index]21 const newNum = num + val22 this.occurences2.set(num, this.occurences2.get(num) - 1)23 this.occurences2.set(newNum, (this.occurences2.get(newNum) || 0) + 1)24 this.nums2[index] = newNum25}2627/**28 * @param {number} tot29 * @return {number}30 */31FindSumPairs.prototype.count = function (tot) {32 let res = 033 for (const num1 of this.nums1) {34 res += this.occurences2.get(tot - num1) || 035 }36 return res37}3839/**40 * Your FindSumPairs object will be instantiated and called as such:41 * var obj = new FindSumPairs(nums1, nums2)42 * obj.add(index,val)43 * var param_2 = obj.count(tot)44 */
Comments
Loading comments...
Tags
leetcode
hash table
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.