Continuous Subarray Sum问题及解法

问题描述:

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.

示例:

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.
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.

问题分析: 

如数组存在题目要求的连续子数组[i,j](i < j),那么必定存在sum(0,i -1) % k = sum(0,j) % k(k != 0)。


过程详见代码:

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


你可能感兴趣的:(Continuous Subarray Sum问题及解法)