303. Range Sum Query - Immutable (Easy)

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

Given an integer array nums, find the sum of the elements between indices i and j (ij), 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.

Solutions

class NumArray {

    private int[] nums;
    private int[] sums;

    private boolean valid = true;

    public NumArray(int[] nums) {

        // verify the validness of given array

        if (nums == null || nums.length == 0) {
            valid = false;
            return;
        }

        this.nums = nums;

        sums = new int[nums.length];
        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 (!valid) {
            return 0;
        }

        return sums[j] - sums[i] + nums[i];
    }
}

Incorrect Solutions

class NumArray {

    private int[] nums;
    private int[] sums;

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

        sums = new int[nums.length];
        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) {
        return sums[j] - sums[i] + nums[i];
    }
}

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2020-07-03 00:26:46

results matching ""

    No results matching ""