高频笔试题23

132 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

今天一共解决了两道题目 1.和可被K整除的子数组 2.和为K的子数组

第一题:

class Solution {
public:
    int subarraysDivByK(vector<int>& nums, int k) {
        unordered_map<int, int> map = {{0, 1}};
        int preSum = 0;
        int cnt = 0;
        
        for(int i = 0; i < nums.size(); i++) {
            preSum += nums[i];
            nums[i] = ((preSum % k + k) % k);
            map[nums[i]]++;
        }

        for(auto & [k, v] : map) {
            cnt += (v * (v - 1)) / 2;
        }
        return cnt;
    }
};

第二题:

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        unordered_map<int, int> map;
        int preSum = 0, cnt = 0;
        map[0] = 1;

        for(auto &n : nums) {
            preSum += n;
            cnt += map[preSum - k];//计算map中存在前缀和preSum - k的个数
            map[preSum]++;
        }
        return cnt;
    }
};

这两道题目很相似,只要能搞懂其中一个,另外一个也就迎刃而解了,这里第二题更好说清楚,我们拿第二题来举例子说明 1.遍历数组nums,从第零个元素到当前元素的和,即前缀和preSum 2.首先定义哈希表,来保存出现过的前缀和的次数,如果preSum - k在哈希表中出现过,则从当前下标i往前右连续的子数组的和为preSum 搞懂了第二题,第一题也是类似的方法步骤

今天一共解决了两道题目 1.和可被K整除的子数组 2.和为K的子数组

第一题:

class Solution {
public:
    int subarraysDivByK(vector<int>& nums, int k) {
        unordered_map<int, int> map = {{0, 1}};
        int preSum = 0;
        int cnt = 0;
        
        for(int i = 0; i < nums.size(); i++) {
            preSum += nums[i];
            nums[i] = ((preSum % k + k) % k);
            map[nums[i]]++;
        }

        for(auto & [k, v] : map) {
            cnt += (v * (v - 1)) / 2;
        }
        return cnt;
    }
};

第二题:

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        unordered_map<int, int> map;
        int preSum = 0, cnt = 0;
        map[0] = 1;

        for(auto &n : nums) {
            preSum += n;
            cnt += map[preSum - k];//计算map中存在前缀和preSum - k的个数
            map[preSum]++;
        }
        return cnt;
    }
};

这两道题目很相似,只要能搞懂其中一个,另外一个也就迎刃而解了,这里第二题更好说清楚,我们拿第二题来举例子说明 1.遍历数组nums,从第零个元素到当前元素的和,即前缀和preSum 2.首先定义哈希表,来保存出现过的前缀和的次数,如果preSum - k在哈希表中出现过,则从当前下标i往前右连续的子数组的和为preSum 搞懂了第二题,第一题也是类似的方法步骤