暑期刷题-Day3

1.303. 区域和检索 - 数组不可变

暑期刷题-Day3_第1张图片 

class NumArray {
public:
    vector sums;

    NumArray(vector& nums) {
        int n = nums.size();
        sums.resize(n + 1);
        for (int i = 0; i < n; i++) {
            sums[i + 1] = sums[i] + nums[i];
        }
    }

    int sumRange(int i, int j) {
        return sums[j + 1] - sums[i];
    }
};

2.1588. 所有奇数长度子数组的和 

暑期刷题-Day3_第2张图片 

class Solution {
public:
    int sumOddLengthSubarrays(vector& arr) {
        int sum = 0;
        int n = arr.size();
        for (int start = 0; start < n; start++) {
            for (int length = 1; start + length <= n; length += 2) {
                int end = start + length - 1;
                for (int i = start; i <= end; i++) {
                    sum += arr[i];
                }
            }
        }
        return sum;
    }
};

3.930. 和相同的二元子数组 

 暑期刷题-Day3_第3张图片

 

 

class Solution {
public:
    int numSubarraysWithSum(vector& nums, int goal) {
        int sum = 0;
        unordered_map cnt;
        int ret = 0;
        for (auto& num : nums) {
            cnt[sum]++;
            sum += num;
            ret += cnt[sum - goal];
        }
        return ret;
    }
};

 

 

你可能感兴趣的:(日常练习,C++,笔记,大数据,c++,c语言,c#,leetcode)