303. Range Sum Query - Immutable - CPP - Solution


  • 0
    Y
    // 303. Range Sum Query - Immutable
    // https://leetcode.com/problems/range-sum-query-immutable/
    #include <iostream>
    #include <vector>
    #include <unordered_map>
    using namespace std;
    class NumArray {
    public:
    	NumArray(const vector<int>& nums) {
    		for (int i = 0; i < nums.size(); ++i) {
    			if (i == 0) {
    				this->hashMap[0] = nums[0];
    			}
    			else if (i >= 1) {
    				this->hashMap[i] = nums[i] + this->hashMap[i - 1];
    			}
    		}
    	}
    
    	int sumRange(const int& i, const int& j) {
    		int result = 0;
    		if (i == 0) {
    			result = this->hashMap[j];
    		}
    		else if (i >= 1) {
    			result = this->hashMap[j] - this->hashMap[i - 1];
    		}
    		return result;
    	}
    private:
    	unordered_map<int, int> hashMap;
    };
    
    int main(int argc, const char** argv) {
    	vector<int> nums = { -2, 0, 3, -5, 2, -1 };
    	NumArray numArray(nums);
    	int i = 0;
    	int j = 5;
    	cout << numArray.sumRange(i, j) << '\n';
    	getchar();
    	return 0;
    }
    // Your NumArray object will be instantiated and called as such:
    // NumArray numArray(nums);
    // numArray.sumRange(0, 1);
    // numArray.sumRange(1, 2);

Log in to reply
 

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