Categories
木有技术

LeetCode 523. Continuous Subarray Sum

https://leetcode.com/problems/continuous-subarray-sum/description/
这道题跟https://leetcode.com/problems/subarray-sum-equals-k/description/ 其实是很像的,但本题的特点就是corner case非常多…

class Solution {
public:
    bool checkSubarraySum(vector<int>& nums, int k) {
        if (k < 0)
            k = -1 * k;
        else if (k == 0)
        {
            // check if there's continuous zeroes
            bool has_zero = false;
            for (int num : nums)
            {
                if (num == 0)
                {
                    if (has_zero == true)
                        return true;
                    has_zero = true;
                }
                else
                    has_zero = false;
            }
            return false;
        }
        if (k == 1 && nums.size() > 1)  // tricky but...
            return true;
        int sum = 0;
        unordered_set<int> sum_records;
        vector<int> targets = {k};
        int last_num = INT32_MAX;
        sum_records.insert(0);
        for (int num : nums)
        {
            sum += num;
            sum_records.insert(sum);
            if (last_num == 0 && num == 0)
                return true;    // n = 0
            while (targets.back() + k <= sum)
                targets.push_back(targets.back() + k);  // prvents calculating dup multiplies
            for (int target : targets)
            {
                if (num != target && sum_records.count(sum - target) > 0)
                    return true;
            }
            last_num = num;
        }
        return false;
    }
};

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.