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

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.

 

Note:

  1. The length of the array won't exceed 10,000.
  2. You may assume the sum of all the numbers is in the range of a signed 32-bit integer.

 

题意解读:该题题意是给定一个数组和一个整数k,求是否存在这样的一个连续的子数组,该子数组的所有数之和可以整除k。

思路分析:该题最直观的思路肯定是暴力求解法,即求出所有的连续子数组,并判断每个连续子数组的所有数之和是否能整除k,这种解法时间复杂度为指数级别,OJ肯定不通过,因此需要优化。如果刷题多的话,遇到这种求子数组或者子矩阵的和的问题,一般会想到要建立子数组或者子矩阵的累加和,本题也是采用这种思路。我们要遍历所有的子数组,然后利用累加和来快速求和。在得到每个子数组之和时,我们先和k比较,如果相同直接返回true,否则再判断,若k不为0,且sum能整除k,同样返回true,最后遍历结束返回false,参见代码如下:

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

 下面的方法比较巧妙,利用了参考资料中提到的一个数学定理:若数a和b分别除以数c,若得到的余数相同,那么(a-b)必定能够整除c。根据这一定理,建立一个哈希表记录余数和当前位置的映射关系,如果累加到当前位置的累加和除以k得到的余数在哈希表中已经存在,说明前面必定存在一个连续子数组的和能够整除k。即nums[i,j]和nums[i,m](注:m>j+1,因为题目要求连续子数组中的元素数目至少为2)都能被k整除,则nums[i,m] - nums[i,j] = nums[j+1,m]必定能被k整除。参考代码如下:

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

参考资料:

http://www.cnblogs.com/grandyang/p/6504158.html

 
posted @ 2017-10-02 14:58  飘舞的雪  阅读(174)  评论(0编辑  收藏  举报