[Leetcode] 303. Range Sum Query - Immutable

whitehousechef·2025년 5월 25일

https://leetcode.com/problems/range-sum-query-immutable/

initial

v easy we just use prefix sum. the only thing that u need to care is

1) when left==0, we need to just return prefix_sum[right]
2) when we are doing

class NumArray {
    private int[] array;

    public NumArray(int[] nums) {
        array = nums; // Reference to original array

we are referring to the same memory address as the original array. So we dont need to set

        // Remove this redundant line: array[0] = nums[0];
        // array[0] already equals nums[0] since they're the same array!

btw you dont need this keyword cuz array and parameter nums have different name so we can distinguish

but if u have same names

class NumArray {
    private int[] array;

    public NumArray(int[] array) {  // Parameter has same name!
        this.array = array;  // ❗ 'this' required to distinguish
        // Without 'this': array = array; (assigns parameter to itself!)
    }
    
    public void someMethod(int[] array) {  // Another case
        this.array = array;  // ❗ 'this' needed here too
    }
}

if u wanna make a copy

prefixSum = nums.clone();

sol

class NumArray {
    private int[] array;

    public NumArray(int[] nums) {
        this.array=nums;
        for(int i =1;i<array.length;i++){
            array[i]+=array[i-1];
        }
        System.out.println(Arrays.toString(array));
    }
    
    public int sumRange(int left, int right) {
        return left==0? array[right]: array[right] - array[left-1];
    }
}

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(left,right);
 */

complexity

n time and space

0개의 댓글