问题描述

给定一个整数数组,返回range sum 落在给定区间[lower, upper] (包含lower和upper)的个数。range sum S(i, j) 表示数组中第i 个元素到j 个元素之和。

Note:

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

Example:

Input: nums = [-2,5,-1], lower = -2, upper = 2,

Output: 3

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

分析

这个题目比较难,楼主第一次面对这种题型,直接缴械投降。参考了各位大神的解题思路,总结了两种解法。一种是TreeMap思路,另外一种是使用segment tree (or binary index tree)。题目寻找需要range sum 在[lower, upper] 之间的个数,满足条件的case用数学公式表达为:

lower <= sum[i] - sum[j] <= upper, i > j, sum[i] is prefix sum of nums at index of i.

也就是

sum[i] - high <=  sum[j] <= sum[i] - lower, i > j, sum[i] is prefix sum of nums at index of i.

(or

lower + sum[j] <=  sum[i] <= sum[j] + higher, i > j, sum[i] is prefix sum of nums at index of i.)

那么我们的问题可以转化为求落在[sum[i] - high,sum[i] - lower] 区间sum[j]的个数, i = 0....n, j < i。

无论是TreeMap还是Segment Tree,总体的时间复杂度都为nlogn。

实现

TreeMap

TreeMap 的key 是prefixsum, value 是相对应的个数。主要使用TreeMap的subMap的方法,求得落在区间内[sum[i] - high, sum[i] - lower]的sum[j]的个数。

 public int countRangeSum(int[] nums, int lower, int upper) {
if(nums == null || nums.length == 0){
return 0;
}
//key is the sum[i], value is the corresponding count
// sum[i] - sum[j] in [lower, upper], transform to find how many sum[j] 在区间[sum[i] - high, sum[i] - lower]。
TreeMap<Long, Integer> map = new TreeMap();
long sum = 0;
int cnt = 0; for(int i = 0; i < nums.length; i++){
sum += nums[i];
//sum[0, i]满足case
if(sum >= lower && sum <= upper){
cnt++;
}
//find sum[j] 的个数that lies in [sum[i] - high, sum[i] - lower]之间
cnt += map.subMap(sum - upper, true, sum - lower, true).values().stream().mapToInt(Integer::valueOf).sum(); map.put(sum, map.getOrDefault(sum, 0) + 1);
}
return cnt;
}

Segment Tree

Segment Tree每个节点保存区间段的范围和落在这个区间内prefix sum的个数。

  class Node {
Node left;
Node right;
//落在区间内的个数
int count;
long min;
long max;
public Node(long min, long max) {
this.min = min;
this.max = max;
}
}
//构建segement tree
private Node buildTree(Long[] valArr, int low, int high) {
if(low > high) return null;
Node root = new Node(valArr[low], valArr[high]);
if(low == high) return root;
int mid = low + (high - low)/2;
root.left = buildTree(valArr, low, mid);
root.right = buildTree(valArr, mid+1, high);
return root;
} private void update(Node root, Long val) {
if(root == null) return;
if(val >= root.min && val <= root.max) {
root.count++;
update(root.left, val);
update(root.right, val);
}
} private int query(Node root, long min, long max) {
if(root == null) return 0;
if(min > root.max || max < root.min) return 0;
if(min <= root.min && max >= root.max) return root.count;
return query(root.left, min, max) + query(root.right, min, max);
} public int countRangeSum(int[] nums, int lower, int upper) { if(nums == null || nums.length == 0) return 0;
int ans = 0;
Set<Long> valSet = new HashSet<Long>();
long sum = 0;
for(int i = 0; i < nums.length; i++) {
sum += (long) nums[i];
valSet.add(sum);
} Long[] valArr = valSet.toArray(new Long[0]); Arrays.sort(valArr);
Node root = buildTree(valArr, 0, valArr.length-1); sum = nums[0];
ans += (sum >= lower && sum <= upper) ? 1:0;
for(int i = 1; i < nums.length; i++) {
//sum[i]
update(root, sum);
//sum[j]
sum += (long) nums[i];
ans += (sum >= lower && sum <= upper) ? 1:0;
ans += query(root, (long)sum - upper, (long)sum - lower);
}
return ans;
}

Leetcode327: Count of Range Sum 范围和个数问题的更多相关文章

  1. leetcode327 Count of Range Sum

    问题描述: 给定一个整数数组nums,返回其所有落在[low, upper]范围内(包含边界)的区间和的数目. 区间和sums(i, j)的定义为所有下标为i到j之间(i ≤ j)的元素的和,包含边界 ...

  2. 【算法之美】你可能想不到的归并排序的神奇应用 — leetcode 327. Count of Range Sum

    又是一道有意思的题目,Count of Range Sum.(PS:leetcode 我已经做了 190 道,欢迎围观全部题解 https://github.com/hanzichi/leetcode ...

  3. 327. Count of Range Sum

    /* * 327. Count of Range Sum * 2016-7-8 by Mingyang */ public int countRangeSum(int[] nums, int lowe ...

  4. [Swift]LeetCode327. 区间和的个数 | Count of Range Sum

    Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.Ra ...

  5. [LeetCode] Count of Range Sum 区间和计数

    Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.Ra ...

  6. LeetCode Count of Range Sum

    原题链接在这里:https://leetcode.com/problems/count-of-range-sum/ 题目: Given an integer array nums, return th ...

  7. [LeetCode] 327. Count of Range Sum 区间和计数

    Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.Ra ...

  8. leetcode@ [327] Count of Range Sum (Binary Search)

    https://leetcode.com/problems/count-of-range-sum/ Given an integer array nums, return the number of ...

  9. 【LeetCode】327. Count of Range Sum

    题目: Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusiv ...

随机推荐

  1. 如何重置IE浏览器

    1.退出所有程序,包括 Internet Explorer.单击“开始”.在“开始搜索”框中键入 inetcpl.cpl 命令,然后按回车键打开“Inetnet 选项”对话框. 2.单击“高级”选项卡 ...

  2. 对python的初步了解

    一,Python简介 Python 是一个高层次的结合了解释性.编译性.互动性和面向对象的脚本语言. Python 的设计具有很强的可读性,相比其他语言经常使用英文关键字,其他语言的一些标点符号,它具 ...

  3. 请问1^x+2^x+3^x+\cdots +n^x的算式是什么呢?

    目录 总结 请问\(1^x+2^x+3^x+\cdots +n^x\)的算式是什么呢? 一.求和式\(\sum\limits_{i=1}^n{i}\)的算式 如何证明求和简式\(\sum_{i=1}^ ...

  4. 论文阅读 | Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks

    简述 在文本语义相似度等句子对的回归任务上,BERT , RoBERTa 拿到sota. 但是,它要求两个句子都被输入到网络中,从而导致巨大开销:从10000个句子集合中找到最相似的sentence- ...

  5. cocoapods 安装使用详解

    http://blog.csdn.net/showhilllee/article/details/38398119 http://www.jianshu.com/p/1222dd6c4271  删除 ...

  6. js练习- 给你一个对象,求有几层

    // 比如这个a中,就有四层.如何算出这四层 const a = { b: 1, c() {}, d: { e: 2, f: { g: 3, h: { i: 4, }, }, j: { k: 5, } ...

  7. 去除npm run dev日志warn记录

    目录 一 babel的一些eslint方法废除了 问题 解决方案 相关文档 二 webpack的loaderUtils.parseQuery()被废弃了 问题 解决方案 相关文档 三 postcss相 ...

  8. 【新】Docker实战总结

    >>> 目录 <<< Docker简介 Docker优势 Docker基本概念 Docker安装使用 Docker常用命令 Docker镜像构建 Docker本地仓 ...

  9. A* 算法讲解

    在看下面这篇文章之前,先介绍几个理论知识,有助于理解A*算法. 启发式搜索:启发式搜索就是在状态空间中的搜索对每一个搜索的位置进行评估,得到最好的位置,再从这个位置进行搜索直到目标.这样可以省略大量无 ...

  10. ubuntu文件权限

    以root身份登录linux. 在某一目录下执行 ls -al,显示类似如下内容: dr-xr-x---. 14 root root 4096 Aug 27 09:38 . dr-xr-xr-x. 2 ...