1. 程式人生 > >leetcode: Continuous Subarray Sum

leetcode: Continuous Subarray Sum

我們 code == true view bool number fun 數組

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

leetcode: Continuous Subarray Sum