leetcode 327. Count of Range Sum

本文介绍了一种有效的算法来计算整数数组中所有子数组的区间和,并统计这些区间和落在指定范围内的数量。该算法避免了朴素算法的O(n^2)复杂度,通过累积和与计数技巧实现了更高效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.
Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive.


Note:
A naive algorithm of O(n2) is trivial. You MUST do better than that.


Example:
Given nums = [-2, 5, -1], lower = -2, upper = 2,
Return 3.

The three ranges are : [0, 0], [2, 2], [0, 2] and their respective sums are: -2, -1, 2.


#include "stdafx.h"
#include<iostream>
//#include<vector>
//#include<algorithm>
using namespace std;



/*Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.
Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive.

Note:
A naive algorithm of O(n2) is trivial. You MUST do better than that.

Example:
Given nums = [-2, 5, -1], lower = -2, upper = 2,
Return 3.
The three ranges are : [0, 0], [2, 2], [0, 2] and their respective sums are: -2, -1, 2.*/


struct Check{
	int lower;
	int upper;
	
public:
	Check(int l, int u){
		lower = l;
		upper = u;
	}
	Check(){}
	bool in_range(int value)
	{
		return (value <= upper) && (value >= lower);
	}
};

int count_num(int*begin,int*end,int lower, int upper)
{
	int num = 0;
	while (end != begin)
	{
		if (*begin >= lower&&*begin <= upper)
			num++;
		begin++;
	}
	return num;
}

int countRangeSum(int* nums, int numsSize, int lower, int upper)
{
	int*sumarray = new int[numsSize];
	memset(sumarray, 0, sizeof(int)*numsSize);
	sumarray[0] = nums[0];

	for (int i = 1; i < numsSize; i++)
	{
		sumarray[i] = sumarray[i - 1] + nums[i];
	}

	/*int countnum = count_if(sumarray, sumarray + numsSize, Check(lower, upper).in_range);
	for (int i = 1; i < numsSize; i++)
	{
		Check check(lower + sumarray[i - 1], upper + sumarray[i - 1]);
		countnum += count_if(sumarray + i, sumarray + numsSize, check.in_range);
	}*/
	int countnum = count_num(sumarray , sumarray + numsSize, lower, upper);;
	for (int i = 1; i < numsSize; i++)
	{
		countnum += count_num(sumarray + i, sumarray + numsSize, lower + sumarray[i - 1], upper + sumarray[i - 1]);
	}
	delete[]sumarray;
	return countnum;
}



int _tmain(int argc, _TCHAR* argv[])
{
	int nums[3] = { -2, 5, -1 };
	cout << countRangeSum(nums, 3, -2, 2);

	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值