3ms java solution, with array, no special i==0 check


  • 1
    Y
    public class NumArray {
        // 7:54pm - 8:01pm
        private int[] nums;
        private int[] sums;
        
        public NumArray(int[] nums) {
            this.nums = nums;
            if (nums == null) {
                return;
            }
            sums = new int[nums.length+1];
            sums[0] = 0;
            for (int i=1; i<=nums.length; i++) {
                sums[i] = sums[i-1] + nums[i-1];
            }
        }
    
        public int sumRange(int i, int j) {
            return sums[j+1] - sums[i];
        }
    }

  • 0
    J

    why java is fast than c++?

    my two c++ codes are just like yours, and both of them are 584ms..

    class NumArray {
    public:
        NumArray(vector<int> &nums) {  
            sums.push_back(0);
            for(int i = 0; i < nums.size(); i++)
                sums.push_back(sums.back() + nums[i]);
        }
    
        int sumRange(int i, int j) {
            return sums[j + 1] - sums[i];
        }
    
    private:
        vector<int> sums;
    };
    
    class NumArray {
    public:
        NumArray(vector<int> &nums) {
            sums = new int[nums.size() + 1];
            sums[0] = 0;
            for(int i = 0; i < nums.size(); i++)
                sums[i + 1] = sums[i] + nums[i];
        }
    
        int sumRange(int i, int j) {
            return sums[j + 1] - sums[i];
        }
    
    private:
        int *sums;
    };
    

  • 0
    Y

    maybe because I used array? I don't know c++ well so I don't know the details of vector. Do you think maybe you can use a fixed-size array


  • 0
    J

    my second code uses dynamic array,but it also runs 584ms...


  • 0
    S

    There is still an error in your code.The for cycle should be
    for (int i=1; i<=nums.length+1; i++) {
    sums[i] = sums[i-1] + nums[i-1];
    }


  • 0
    Y

    did you test it? i think you will get a array index out of bound error.


  • 0
    S

    Not really.I submitted my code and it has been accepted.Think about that,when i=nums.length+1,it will jump out the cycle.So the last executed i is i=nums.length,then nums[i-1] won't out of bound.


  • 0
    Y

    i resubmitted my code and it was accepted. maybe you can copy and paste my code and submit it yourself.


  • 0

    My solution is the same as you.


Log in to reply
 

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