concise c++ solution using presum and hashmap


  • 0
    X
    class Solution {
    public:
        bool checkSubarraySum(vector<int>& nums, int k) {
            if (k < 0) k = -k;
            for (int i = 0; i < nums.size(); i++) {
    			nums[i] = (k > 0)? nums[i] % k : nums[i];
    		}
    		
    		unordered_map<int, vector<int>> mymap;
    		vector<int> cumsum{0};
    		mymap[0].push_back(0);
    		for (int i = 0; i < nums.size(); i++) {
    			int back = (k > 0)?(cumsum.back() + nums[i]) % k : cumsum.back() + nums[i];
    			if (mymap.find(back) != mymap.end() && (i + 1 - mymap[back][0] >= 2)) {
    				return true;
    			}
    			
    			cumsum.push_back(back);
    			mymap[back].push_back(i + 1);
    		}
    		return false;
        }
    };
    

Log in to reply
 

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