LeetCode筆記:303. Range 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.

大意:

給出一個整型數組 nums,尋找其中位置 i 與 j 之間元素的和,包括 i 與 j 元素。
例子:

給出 nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
注意:

  1. 你可以假設數組不會變。
  2. 會多次調用 sumRange 函數。

思路:

這道題其實不是考某種算法,而是考實現的方式。題目給出了一個初始化函數一個計算和的函數,如下:

public class NumArray {
    
    public NumArray(int[] nums) {
        
    }

    public int sumRange(int i, int j) {
        
    }
}

一般的實現方法很直接,定義一個變量 nums 數組,在初始化函數中賦值,在求和函數中直接遍歷計算就行了很簡單。但是如果直接這樣做,答案會超時。題目明確指出求和函數會被多次調用,因此這里應該盡量簡化求和函數,而把復雜度放在初始化時。

我們在初始化時,直接將每個元素的值改為從第一個元素到當前元素的和,這樣在初始化時遍歷計算一次。然后在求和時,只需要很簡單地用兩個位置的值相減就可以得出中間元素的和了。

代碼(Java):

public class NumArray {
    int[] nums;
    
    public NumArray(int[] nums) {
        for (int i = 1; i < nums.length; i++)
            nums[i] += nums[i-1];
        
        this.nums = nums;
    }

    public int sumRange(int i, int j) {
        if (i == 0) return nums[j];
        else return nums[j] - nums[i-1];
    }
}

合集:https://github.com/Cloudox/LeetCode-Record


查看作者首頁

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容