zoukankan      html  css  js  c++  java
  • LeetCode -- Range Sum Query

    geQuestion:

    Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

    Example:

    Given nums = [-2, 0, 3, -5, 2, -1]
    
    sumRange(0, 2) -> 1
    sumRange(2, 5) -> -1
    sumRange(0, 5) -> -3
    

    Note:

    1. You may assume that the array does not change.
    2. There are many calls to sumRange function.

    Analysis:

    给出一个整数数组,得出i与j之间的数字之和(i<=j)。你可以假设数组不会改变,并且他们可以调用多次sunRange函数。

    Answer:

    解法一:

    public class NumArray {
        int[] num;
        public NumArray(int[] nums) {
            this.num = nums;
        }
        public int sumRange(int i, int j) {
            int res = 0;
            for(int k=i; k<j+1; k++) {
                res += num[k];
            }
            return res;
        }
        
    }
    
    
    // Your NumArray object will be instantiated and called as such:
    // NumArray numArray = new NumArray(nums);
    // numArray.sumRange(0, 1);
    // numArray.sumRange(1, 2);

    解法二:由于题目中说会多次调用该函数,计算某个区间内的和,如果按照上面的解法,当数组过大时,会导致多次重复计算和,因此我们可以想办法存储中间计算的结果来简化计算。 方法就是一次存储从第0个元素到第i个元素计算的中间结果,当求某个区间的和时,直接用大区间减去小区间的和即可。

    public class NumArray {
    
        int[] num;
        public NumArray(int[] nums) {
            if(nums == null)
                num = null;
            else if(nums.length == 0)
                num = nums;
            else {
                num = new int[nums.length];
                num[0] = nums[0];
                for(int i=1; i<nums.length; i++) {
                    num[i] = nums[i] + num[i-1];
                }
                for(int i=0; i<num.length; i++) 
                    System.out.print(num[i] + " * ");
                System.out.println();
            }
            
    
        }
        public int sumRange(int i, int j) {
            if(i == 0)
                return num[j];
            else return num[j] - num[i-1];
        }
    }
    
    
    // Your NumArray object will be instantiated and called as such:
    // NumArray numArray = new NumArray(nums);
    // numArray.sumRange(0, 1);
    // numArray.sumRange(1, 2);
  • 相关阅读:
    网页字体大小控制
    表格文本框搜索匹配
    表格展开和关闭
    表格复选框控制行高亮
    jquery表单验证
    文本框变大变小效果--jQuery
    滚动条高度变化jQuery
    点击标题显示隐藏效果--jQuery
    jQuery练习2-1
    jQuery练习2
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/5188699.html
Copyright © 2011-2022 走看看