Simple O(1) C# solution.


  • 0
    *

    public class NumArray {

    private int[] sum;
    
    public NumArray(int[] nums) {
    	
    	sum = new int[nums.Length];
    	
    	int totalSum = 0;
    	for(int i=0; i<nums.Length; i++)
    	{
    		sum[i] = totalSum + nums[i];
    		totalSum +=nums[i];
    	}
    }
    
    public int SumRange(int i, int j) {
        
    	if(i == 0 )
    		return sum[j];
    	return(sum[j]-sum[i-1]);
    }
    

    }


Log in to reply
 

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