Javascript time limit exceeded error


  • 0
    M

    Still trying to get used to LeetCode format and I don't understand why
    this simple solution gets a time limit exceeded error. Any help?

    /**
     * @constructor
     * @param {number[]} nums
     */
    var NumArray = function(nums) {
      this.nums = nums;
    };
    
    /**
     * @param {number} i
     * @param {number} j
     * @return {number}
     */
    NumArray.prototype.sumRange = function(i, j) {
      var sum = 0;
      while (i <= j) {
        sum += this.nums[i];
        i++;
      }
      console.log(sum);
      return sum;
    };

  • 0
    P

    your code needs o(j-i) to find the answer, try a o(1) way

    if you save the numbers simply, it will cost you more time doing sum

    now the problem is that you will do a lot of sum in a array,so do more work on saving the array,not on doing sum.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.