1
头图

Regions and retrieval-immutable arrays

Title description: Given an integer array nums, find the sum of the elements in the range from index i to j (i ≤ j), including two points i and j.

Implement the NumArray class:

  • NumArray(int[] nums) uses the array nums to initialize the object
  • int sumRange(int i, int j) returns the sum of the elements in the array nums from index i to j (i ≤ j), including two points i and j (that is, sum(nums[i], nums[i + 1] , ..., nums[j]))

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/range-sum-query-immutable/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Accumulate
First, declare an int array type member variable nums NumArray sumRange the method 0614ab153c1733 is to add the element values at position left~right
package com.kaesar.leetcode;

public class LeetCode_303 {
    public static void main(String[] args) {
        // 测试用例
        NumArray numArray = new NumArray(new int[]{-2, 0, 3, -5, 2, -1});
        System.out.println(numArray.sumRange(0, 2)); // return 1 ((-2) + 0 + 3)
        System.out.println(numArray.sumRange(2, 5)); // return -1 (3 + (-5) + 2 + (-1))
        System.out.println(numArray.sumRange(0, 5)); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1))
    }
}

class NumArray {

    private int[] nums;

    public NumArray(int[] nums) {
        this.nums = nums;
    }

    public int sumRange(int left, int right) {
        int result = 0;
        for (int i = left; i <= right; i++) {
            result += nums[i];
        }
        return result;
    }
[Daily Message] in the morning, let the mood fly in the sun, face the unknown, be brave and fearless; let the happy heart follow, relaxed and bright.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!