Header Ad

Leetcode Range Sum Query - Immutable problem solution

In this Leetcode Range Sum Query - Immutable problem solution You are given an integer array nums, handle multiple queries of the following type:

Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.

Implement the NumArray class:

  1. NumArray(int[] nums) Initializes the object with the integer array nums.
  2. int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).

Leetcode Range Sum Query - Immutable problem solution


Problem solution in Python.

class NumArray:

    def __init__(self, nums: List[int]):
        self.lst = []
        sum_ = 0
        for i in nums:
            sum_ += i
            self.lst.append(sum_)

    def sumRange(self, i: int, j: int) -> int:
        if i > 0 and j >0:
            return self.lst[j] - self.lst[i-1]
        else:
            return self.lst[j]



Problem solution in Java.

class NumArray {
    int[] array;
    public NumArray(int[] nums) {
        if(nums.length > 0) {
            array = new int[nums.length];
            array[0] = nums[0];
            for(int i = 1; i < nums.length; ++i) {
                array[i] = array[i - 1] + nums[i];
            }
        }
    }

    public int sumRange(int i, int j) {
        if (i < 0 || j > array.length) {
            return 0;
        }
        if (i == 0) {
            return array[j];
        }
        return array[j] - array[i - 1];
    }

    public static void main(String[] args) {
        int[] nums = {-2, 0, 3, -5, 2, -1};
        int i = 0;
        int j = 5;
        NumArray obj = new NumArray(nums);
        int param_1 = obj.sumRange(i,j);
        System.out.println(param_1);
    }
}


Problem solution in C++.

class NumArray {
public:
vector sum;

NumArray(vector<int>& nums) {
    int prev=0;
     sum.push_back(0);
    for(int i=0; i<nums.size(); i++)
    {
        prev+=nums[i];
        sum.push_back(prev);
    }
    
}

int sumRange(int i, int j) {
    return sum[j+1]-sum[i];
}
};


Problem solution in C.

typedef int NumArray;

NumArray* numArrayCreate(int* nums, int numsSize) {
    for(int i = 1; i < numsSize; i++) {
         nums[i] += nums[i-1];
    }
    return (NumArray*)nums;
}

int numArraySumRange(NumArray* obj, int left, int right) {
    if(left == 0) return obj[right];
    return obj[right] - obj[left-1];
}

void numArrayFree(NumArray* obj) {
    free(obj);
}


Post a Comment

0 Comments