美文网首页
区域和检索 - 数组不可变

区域和检索 - 数组不可变

作者: xin激流勇进 | 来源:发表于2019-04-20 19:53 被阅读0次
    给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange()
    
    sumRange(0, 2) -> 1
    sumRange(2, 5) -> -1
    sumRange(0, 5) -> -3
    package structures;
    
    class NumArray {
    
        private int[] sum;
    
        public NumArray(int[] nums) {
            if (nums.length > 0) {
                sum = new int[nums.length + 1];
                // 0表示一个元素也没有 2表示两个元素的和
                sum[0] = 0;
                for (int i = 1; i < nums.length; i++) {
                    sum[i] = sum[i - 1] + nums[i - 1];
                }
            }
        }
    
        public int sumRange(int i, int j) {
            return sum[j + 1] - sum[i];
        }
    
        public static void main(String[] args) {
            int[] nums = {-2, 0, 3, -5, 2, -1};
            NumArray obj = new NumArray(nums);
            int param_1 = obj.sumRange(1, 4);
            System.out.println(param_1);
        }
    }
    
    /**
     * Your NumArray object will be instantiated and called as such:
     * NumArray obj = new NumArray(nums);
     * int param_1 = obj.sumRange(i,j);
     */
    
    package structures;
    
    class NumArray {
    
        private int[] sum;
    
        public NumArray(int[] nums) {
            if (nums.length > 0) {
                sum = new int[nums.length + 1];
                // 0表示一个元素也没有 2表示两个元素的和
                sum[0] = 0;
                for (int i = 1; i < nums.length; i++) {
                    sum[i] = sum[i - 1] + nums[i - 1];
                }
            }
        }
    
        public int sumRange(int i, int j) {
            return sum[j + 1] - sum[i];
        }
    
        public static void main(String[] args) {
            int[] nums = {-2, 0, 3, -5, 2, -1};
            NumArray obj = new NumArray(nums);
            int param_1 = obj.sumRange(1, 4);
            System.out.println(param_1);
        }
    }
    
    /**
     * Your NumArray object will be instantiated and called as such:
     * NumArray obj = new NumArray(nums);
     * int param_1 = obj.sumRange(i,j);
     */
    

    相关文章

      网友评论

          本文标题:区域和检索 - 数组不可变

          本文链接:https://www.haomeiwen.com/subject/ufolgqtx.html