摄影网站建设的意义,做网站 零基础从哪里开始学,河北搜索引擎推广价格,网站制作公司重庆文章目录1. 题目2. 解题1. 题目
给你两个整数数组 nums1 和 nums2 #xff0c;请你实现一个支持下述两类查询的数据结构#xff1a;
累加 #xff0c;将一个正整数加到 nums2 中指定下标对应元素上。计数 #xff0c;统计满足 nums1[i] nums2[j] 等于指定值的下标对 (i,…
文章目录1. 题目2. 解题1. 题目
给你两个整数数组 nums1 和 nums2 请你实现一个支持下述两类查询的数据结构
累加 将一个正整数加到 nums2 中指定下标对应元素上。计数 统计满足 nums1[i] nums2[j] 等于指定值的下标对 (i, j) 数目0 i nums1.length 且 0 j nums2.length。
实现 FindSumPairs 类
FindSumPairs(int[] nums1, int[] nums2) 使用整数数组 nums1 和 nums2 初始化 FindSumPairs 对象。void add(int index, int val) 将 val 加到 nums2[index] 上即执行 nums2[index] val 。int count(int tot) 返回满足 nums1[i] nums2[j] tot 的下标对 (i, j) 数目。
示例
输入
[FindSumPairs, count, add, count, count, add, add, count]
[[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]]
输出
[null, 8, null, 2, 1, null, null, 11]解释
FindSumPairs findSumPairs new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]);
findSumPairs.count(7); // 返回 8 ; 下标对 (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) 满足 2 5 7 下标对 (5,1), (5,5) 满足 3 4 7
findSumPairs.add(3, 2); // 此时 nums2 [1,4,5,4,5,4]
findSumPairs.count(8); // 返回 2 下标对 (5,2), (5,4) 满足 3 5 8
findSumPairs.count(4); // 返回 1 下标对 (5,0) 满足 3 1 4
findSumPairs.add(0, 1); // 此时 nums2 [2,4,5,4,5,4]
findSumPairs.add(1, 1); // 此时 nums2 [2,5,5,4,5,4]
findSumPairs.count(7); // 返回 11 下标对 (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) 满足 2 5 7 下标对 (5,3), (5,5) 满足 3 4 7提示
1 nums1.length 1000
1 nums2.length 10^5
1 nums1[i] 10^9
1 nums2[i] 10^5
0 index nums2.length
1 val 10^5
1 tot 10^9
最多调用 add 和 count 函数各 1000 次来源力扣LeetCode 链接https://leetcode-cn.com/problems/finding-pairs-with-a-certain-sum 著作权归领扣网络所有。商业转载请联系官方授权非商业转载请注明出处。 2. 解题
nums2 的长度比较长对其数字进行哈希计数add 的时候更新哈希计数count 的时候遍历 nums1 在 哈希map 中查找 tot - nums1_i
class FindSumPairs {unordered_mapint,int m;vectorint v1, v2;
public:FindSumPairs(vectorint nums1, vectorint nums2) {v1 nums1;v2 nums2;for(auto n : nums2)m[n];//哈希计数}void add(int index, int val) {m[v2[index]]--;//原来的数字少一个v2[index] val;//更新值m[v2[index]];//新的数字多一个}int count(int tot) {int ans 0;for(auto n : v1){if(m.find(tot-n) ! m.end())//哈希查找ans m[tot-n];}return ans;}
};360 ms 72 MB C 我的CSDN博客地址 https://michael.blog.csdn.net/
长按或扫码关注我的公众号Michael阿明一起加油、一起学习进步