Continuous Subarray Sum

[leetcode]Continuous Subarray Sum

链接:https://leetcode.com/problems/continuous-subarray-sum/description/

Question

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:
The length of the array won't exceed 10,000.
You may assume the sum of all the numbers is in the range of a signed 32-bit integer.

Solution 1[MLE]

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

开一个二维数组,结果超时了。。

Solution 2[Accepted]

// 利用了一个定理:用数字a和数字b分别除以数字c,如果得到的余数相同,那么(a-b)必定能整除c
// 也就是说每次我将一个累积和比如sum[i]%k=a放入一个集合,如果后面有一个j使得sum[j]%k也等于a,说明(i, j]区间就是整除k的
class Solution {
public:
  bool checkSubarraySum(vector<int>& nums, int k) {
    if (nums.size() <= 1) return false;
    if (k == 0) {
      for (int i = 0; i < nums.size(); i++)
        if (nums[i] != 0)
          return false;
      return true;
    }
    set<int> myset;
    int runningSum = 0;
    for (int i = 0; i < nums.size(); i++) {
      runningSum += nums[i];
      int modNum = runningSum%k;
      // 注意累积和可以直接整除k的话也可以,但是必须数量在1个以上
      if (modNum == 0 && i > 0) return true;
      if (myset.count(modNum) != 0) {
        return true;
      } else {
        myset.insert(modNum);
      }
    }
    return false;
  }
};

思路:只需要遍历一次数组,学习了。。具体做法看注释

你可能感兴趣的:(leetcode,动态规划)