[力扣] 算法 303 (C#)

303. 区域和检索 – 数组不可变

public class NumArray {
    readonly int[] sum;
    public NumArray(int[] nums)
    {
        if (nums != null)
        {
            sum = new int[nums.Length];
            if (nums.Length > 0)
                sum[0] = nums[0];
            for (var i = 1; i < sum.Length; i++)
                sum[i] += sum[i - 1] + nums[i];
        }
    }
    public int SumRange(int i, int j) => sum[j] - (i == 0 ? 0 : sum[i - 1]);
}

发表评论