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

    Description:

    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.

    题目大意:给定一个数组和两个下标i,j,求出i和j之间的数字的和。包含i,j。

    思路:这题非常简单,按照最简单的思路做,就是循环i到j求和。

    实现代码:

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

    但是这样就没意思了,后台的调用方式是连续调用一个数组的sumRange方法。但是上面的解法就会有非常多的重复计算。所以还可以优化,就是在初始化的时候把所有的和都算出来,在返回的时候直接获取就行了。用sum[i]表示0~i的和,则i~j的和就是sum[j] - sum[i-1]。nums为空,i=0,等情况要特殊考虑。

    实现代码:

    public class NumArray {
        
        private int[] nums;
        
        private int[] sums;
    
        public NumArray(int[] nums) {
            if(nums != null) {
                this.nums = nums;
            }
            else
                this.nums = new int[0];
            sums = new int[nums.length];
            if(nums.length != 0)
                sums[0] = nums[0];
            for(int i=1; i<nums.length; i++) {
                sums[i] = sums[i-1] + nums[i]; 
            }
        }
    
        public int sumRange(int i, int j) {
            if(nums == null || nums.length == 0) return 0;
            if(i == 0) return sums[j];
            return sums[j] - sums[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);

    效率明显提高了。

  • 相关阅读:
    我知道点redis-数据结构与对象
    白帽子-第十四章 PHP安全
    白帽子-第二篇 客户端脚本安全
    网络编程
    inline的作用
    Windows静态库和动态库区别
    简单实现图片上传预览
    Java 通用正则表达式
    C#+Mysql 图片数据存储
    FileUpload转换为字节
  • 原文地址:https://www.cnblogs.com/wxisme/p/5207882.html
Copyright © 2011-2022 走看看