美文网首页
523. Continuous Subarray Sum

523. Continuous Subarray Sum

作者: 叶孤陈 | 来源:发表于2017-06-08 12:28 被阅读0次

Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer.

Example 1:

Input: [23, 2, 4, 6, 7],  k=6
Output: True
Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.

Example 2:

Input: [23, 2, 6, 4, 7],  k=6
Output: True
Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42.

解题思路
本题和Contiguous Array很类似,解题思路基本一致,但一开始要想到使用hash table的思路也不是很容易,本题的核心思想是要想到使用求余的方法,遍历数组,依次叠加当前数组元素并将和对K求余,求余结果存入哈希表中,如果遍历到当前位置,求余结果存在于哈希表中,则表明上一次求余结果相同的位置到当前位置的子数组的和为k的倍数,如果位置相差> 1,则返回true.

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

相关文章

网友评论

      本文标题:523. Continuous Subarray Sum

      本文链接:https://www.haomeiwen.com/subject/fhugfxtx.html