leetcode 327. Count of Range Sum

ゞ 浴缸里的玫瑰 2022-08-20 02:18 251阅读 0赞

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.

  1. #include "stdafx.h"
  2. #include<iostream>
  3. //#include<vector>
  4. //#include<algorithm>
  5. using namespace std;
  6. /*Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.
  7. Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive.
  8. Note:
  9. A naive algorithm of O(n2) is trivial. You MUST do better than that.
  10. Example:
  11. Given nums = [-2, 5, -1], lower = -2, upper = 2,
  12. Return 3.
  13. The three ranges are : [0, 0], [2, 2], [0, 2] and their respective sums are: -2, -1, 2.*/
  14. struct Check{
  15. int lower;
  16. int upper;
  17. public:
  18. Check(int l, int u){
  19. lower = l;
  20. upper = u;
  21. }
  22. Check(){}
  23. bool in_range(int value)
  24. {
  25. return (value <= upper) && (value >= lower);
  26. }
  27. };
  28. int count_num(int*begin,int*end,int lower, int upper)
  29. {
  30. int num = 0;
  31. while (end != begin)
  32. {
  33. if (*begin >= lower&&*begin <= upper)
  34. num++;
  35. begin++;
  36. }
  37. return num;
  38. }
  39. int countRangeSum(int* nums, int numsSize, int lower, int upper)
  40. {
  41. int*sumarray = new int[numsSize];
  42. memset(sumarray, 0, sizeof(int)*numsSize);
  43. sumarray[0] = nums[0];
  44. for (int i = 1; i < numsSize; i++)
  45. {
  46. sumarray[i] = sumarray[i - 1] + nums[i];
  47. }
  48. /*int countnum = count_if(sumarray, sumarray + numsSize, Check(lower, upper).in_range);
  49. for (int i = 1; i < numsSize; i++)
  50. {
  51. Check check(lower + sumarray[i - 1], upper + sumarray[i - 1]);
  52. countnum += count_if(sumarray + i, sumarray + numsSize, check.in_range);
  53. }*/
  54. int countnum = count_num(sumarray , sumarray + numsSize, lower, upper);;
  55. for (int i = 1; i < numsSize; i++)
  56. {
  57. countnum += count_num(sumarray + i, sumarray + numsSize, lower + sumarray[i - 1], upper + sumarray[i - 1]);
  58. }
  59. delete[]sumarray;
  60. return countnum;
  61. }
  62. int _tmain(int argc, _TCHAR* argv[])
  63. {
  64. int nums[3] = { -2, 5, -1 };
  65. cout << countRangeSum(nums, 3, -2, 2);
  66. system("pause");
  67. return 0;
  68. }

发表评论

表情:
评论列表 (有 0 条评论,251人围观)

还没有评论,来说两句吧...

相关阅读