C++ O(n) Time, O(k) Space


  • 0
    F
    class Solution {
    public:
        bool checkSubarraySum(vector<int>& nums, int k) {
            if (nums.size() < 2)
                return false;
            unordered_map<int, int> reminders;
            reminders[0] = -1;
            k = abs(k);
            int sum = 0;
            for (int i = 0 ; i < nums.size(); ++ i)
            {
                sum += nums[i];
                if (k != 0)
                    sum = sum % k;
                auto iter = reminders.find(sum);
                if (iter != reminders.end())
                {
                    if (iter->second < i - 1)
                        return true;
                }else
                    reminders[sum] = i;
            }
            return false;
            
        }
    };
    

Log in to reply
 

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