找出和为指定值的下标对-c语言暴力解法

找出和为指定值的下标对-c语言暴力解法,第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

这题我们常规暴力解法如下:

typedef struct {
    int *num1;
    int *num2;
    int num1size;
    int num2size;

} FindSumPairs;


FindSumPairs* findSumPairsCreate(int* nums1, int nums1Size, int* nums2, int nums2Size) {

    FindSumPairs *fp=(FindSumPairs *)malloc(sizeof(FindSumPairs));
    int i;
    fp->num1=(int *)malloc(sizeof(int)*nums1Size);
    fp->num2=(int *)malloc(sizeof(int)*nums2Size);
    
    for(i=0;i<nums1Size;i++){
        fp->num1[i]=nums1[i];
        
    }
     for(i=0;i<nums2Size;i++){
        fp->num2[i]=nums2[i];
        
    }
   
    fp->num1size=nums1Size;
    fp->num2size=nums2Size;
    return fp;
}

void findSumPairsAdd(FindSumPairs* obj, int index, int val) {
   obj->num2[index]=obj->num2[index]+val;

}

int findSumPairsCount(FindSumPairs* obj, int tot) {
    int i,j;
    int n=0;
    
    for(i=0;i<obj->num1size;i++){
       
         for(j=0;j<obj->num2size;j++){
             if( obj->num1[i]+obj->num2[j]==tot)
             n++;
         }
    }
    return n;


}

void findSumPairsFree(FindSumPairs* obj) {

}

/**
 * Your FindSumPairs struct will be instantiated and called as such:
 * FindSumPairs* obj = findSumPairsCreate(nums1, nums1Size, nums2, nums2Size);
 * findSumPairsAdd(obj, index, val);
 
 * int param_2 = findSumPairsCount(obj, tot);
 
 * findSumPairsFree(obj);
*/

当然使用哈希表是个很好的方法,可以尝试一下,把我们的值映射到哈希表中。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/717228.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存