Given an integer array (index from 0 to n-1, where n is the size of this array), and an query list. Each query has two integers [start, end]. For each query, calculate the sum number between index start and end in the given array, return the result list.

Example

For array [1,2,7,8,5], and queries [(0,4),(1,2),(2,4)], return [23,9,20].

Analysis:
Use an array to save the sum from 0 to i. Then for query [i, j], we shoud return sum[j] - sum[i - 1].

 /**
* Definition of Interval:
* public classs Interval {
* int start, end;
* Interval(int start, int end) {
* this.start = start;
* this.end = end;
* }
*/
public class Solution {
/**
*@param A, queries: Given an integer array and an query list
*@return: The result list
*/
public ArrayList<Long> intervalSum(int[] A,
ArrayList<Interval> queries) { ArrayList<Long> list = new ArrayList<Long>();
if (A == null || A.length == ) return list;
if (queries == null || queries.size() == ) return list; long[] sum = new long[A.length]; for (int i = ; i < sum.length; i++) {
if (i == ) {
sum[i] = A[i];
} else {
sum[i] += sum[i - ] + A[i];
}
} for (int i = ; i < queries.size(); i++) {
Interval interval = queries.get(i);
if (interval.start == ) {
list.add(sum[interval.end]);
} else {
list.add(sum[interval.end] - sum[interval.start - ]);
}
}
return list;
}
}

Interval Sum II

Given an integer array in the construct method, implement two methods query(start, end)and modify(index, value):

  • For query(startend), return the sum from index start to index end in the given array.
  • For modify(indexvalue), modify the number in the given index to value
Example

Given array A = [1,2,7,8,5].

  • query(0, 2), return 10.
  • modify(0, 4), change A[0] from 1 to 4.
  • query(0, 1), return 6.
  • modify(2, 1), change A[2] from 7 to 1.
  • query(2, 4), return 14.

Analysis:

As the value in the array may change, so it is better to build a segement tree. If the value in the tree is changed, we also need to update its parent node.

 public class Solution {
/* you may need to use some attributes here */ SegmentTreeNode root; /**
* @param A:
* An integer array
*/
public Solution(int[] A) {
if (A == null || A.length == )
return;
root = build(A, , A.length - );
} private SegmentTreeNode build(int[] A, int start, int end) {
if (A == null || start < || end >= A.length)
return null;
SegmentTreeNode root = new SegmentTreeNode(start, end, );
if (start == end) {
root.sum = A[start];
} else {
int mid = (end - start) / + start;
root.left = build(A, start, mid);
root.right = build(A, mid + , end);
root.sum = root.left.sum + root.right.sum;
}
return root;
} public long query(int start, int end) {
if (root == null || start > end)
return ;
return helper(root, Math.max(, start), Math.min(end, root.end));
} public long helper(SegmentTreeNode root, int start, int end) {
if (root.start == start && root.end == end) {
return root.sum;
} int mid = (root.start + root.end) / ;
if (start >= mid + ) {
return helper(root.right, start, end);
} else if (end <= mid) {
return helper(root.left, start, end);
} else {
return helper(root.left, start, mid) + helper(root.right, mid + , end);
}
} public void modify(int index, int value) {
if (root == null)
return;
if (index < root.start && index > root.end)
return;
modifyHelper(root, index, value);
} public void modifyHelper(SegmentTreeNode root, int index, int value) {
if (root.start == root.end && root.start == index) {
root.sum = value;
return;
} int mid = (root.start + root.end) / ;
if (index >= mid + ) {
modifyHelper(root.right, index, value);
} else {
modifyHelper(root.left, index, value);
}
root.sum = root.left.sum + root.right.sum; }
} class SegmentTreeNode {
public int start, end, sum;
public SegmentTreeNode left, right; public SegmentTreeNode(int start, int end, int sum) {
this.start = start;
this.end = end;
this.sum = sum;
this.left = this.right = null;
}
}

Interval Sum I && II的更多相关文章

  1. Lintcode: Interval Sum II

    Given an integer array in the construct method, implement two methods query(start, end) and modify(i ...

  2. 1. Two Sum I & II & III

    1. Given an array of integers, return indices of the two numbers such that they add up to a specific ...

  3. [Leetcode][JAVA] Path Sum I && II

    Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addi ...

  4. LeetCode:Combination Sum I II

    Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combin ...

  5. LeetCode:Path Sum I II

    LeetCode:Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such ...

  6. Nested List Weight Sum I & II

    Nested List Weight Sum I Given a nested list of integers, return the sum of all integers in the list ...

  7. Two Sum I & II

    Two Sum I Given an array of integers, find two numbers such that they add up to a specific target nu ...

  8. Lintcode: Interval Sum

    Given an integer array (index from 0 to n-1, where n is the size of this array), and an query list. ...

  9. Leetcode 39 40 216 Combination Sum I II III

    Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combin ...

随机推荐

  1. Uploadify提示-Failed,上传不了文件,跟踪onUploadError事件,errorMsg:2156 SecurityError Error #2156 null

    在使用Uploadify上传文件时,提示-Failed,上传不了文件 折腾中.....,没有结果.....%>_<%... 于是跟踪onUploadError事件,发现 errorMsg: ...

  2. java 读写 excle 完整版

    pom.xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</a ...

  3. Redis分布式锁的实现

    前段时间,我在的项目组准备做一个类似美团外卖的拼手气红包[第X个领取的人红包最大],基本功能实现后,就要考虑这一操作在短时间内多个用户争抢同一资源的并发问题了,类似于很多应用如淘宝.京东的秒杀活动场景 ...

  4. GS 服务器端开启webservice 远程调试的方法

    1. 修改 安装目录下 web.config的文件. 一般目录为: C:\Program Files\GenerSoft\bscw_local\web.config 为了保证安全想把文件备份一下. 2 ...

  5. dx、aapt工具

    1.DX命令: Dalvik虚拟机不能直接运行Java代码编译出来的文件,只能运行.dex文件,所以需要将.class,.jar等文件通过DX工具转换成.dex文件. 2.AAPT命令 一个Andro ...

  6. ES6学习笔记(三):与迭代相关的新东东

    Symbol 概念 Symbol:一种新的原始数据类型,表示独一无二的值. 注意:Symbol函数的参数只是表示对当前Symbol值的描述,因此相同参数的Symbol函数的返回值是不相等的. // 没 ...

  7. python自动化之爬虫模拟登录

    http://selenium-python.readthedocs.io/locating-elements.html ####################################### ...

  8. UVA - 10129 Play on Words (欧拉回路+并查集)

    思路: 分别存下每个字符串的首尾字符,以字符为结点,单词看作一条变,就变成了求欧拉回路了,先判断下图是否连通,然后根据欧拉回路的结论:最多只能有两个点的入读不等于初读,而且必须是一个点的出度恰好比入度 ...

  9. catch/finally中不应使用 writer.flush()

    在开发中遇到了一个问题,关闭流的时候会出现某种莫名其妙的错误.后来一个巧合看到了这个解决方法. 先看问题(知道答案以后,才知道是这里出错了) FileWriter writer = null; Str ...

  10. Could not load file or assembly 'Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies

    my shurufa  huai diao le 1\ first   you need  install     " SQLSysClrTypes_x86.msi  " 2\   ...