C++ solution O(N) solution


  • 0
    G
    class Solution {
    public:
        bool checkSubarraySum(vector<int>& nums, int k) {
            
            unordered_map<int,int> m;
            vector<int> ps;
            partial_sum(nums.begin(),nums.end(),back_inserter(ps),[&](int sum, const int num)->int{
                sum += num;
                return (k != 0 ? sum % k : sum);
            });
            
            m[0] = -1;
            
            for(int i = 0; i < ps.size(); ++i){
                if(m.find(ps[i]) != m.end()){
                    if(i - m[ps[i]] >= 2){
                        return true;
                    }
                }
                
                m.insert({ps[i],i});
            }
            
            return false;
        }
    };
    

Log in to reply
 

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