leetcode(303)Range Sum Query - Immutable js代碼實現

Sum Query - Immutable

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

JavaScript代碼實現

/**
 * @constructor
 * @param {number[]} nums
 */
var NumArray = function(nums) {
	this.nums = nums;
	for(i = 1; i < nums.length; i++){
		this.nums[i] += this.nums[i - 1];
	}
};

/**
 * @param {number} i
 * @param {number} j
 * @return {number}
 */
NumArray.prototype.sumRange = function(i, j) {
	if(i == 0){
		return this.nums[j];
	}
	return this.nums[j] - this.nums[i - 1];
};

剛剛看到這個問題的時候可能會想到用循環來查找每次所需要的區間進行相加,但是這種方法提交上去不會accept,因爲這並不是最佳的方法,注意題目中所說的,You may assume that the array does not change.我們可以假設數組是不變的,那麼我們可以在NumArray 類中一次求出所有從第一個數到第n個數的和,根據提示,在sumRange函數中寫出需要的函數語句即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章