1. 程式人生 > >LeetCode: -Dynamic Programming-Continuous Subarray Sum[523]

LeetCode: -Dynamic Programming-Continuous Subarray Sum[523]

題目

非負整數陣列中,連續子陣列(子陣列長度最小為2)和為k的倍數,是否存在的問題。

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.

解法:

暴力破解法,容易理解,複雜度O(n^2)

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

O(n)時間複雜度,O(k)空間複雜度(Java)map

思想: 用子陣列和對k取模,當兩次取模得到的餘數相同時,這這兩次取模時的位置構成的子區間陣列和為k的倍數。

過程:遍歷整個陣列,用遍歷和對k取模,在map(map鍵值對中存放的是模和相應的位置)中查詢這個模,如果找到了,判斷兩個位置之間間隔是否大於等於2,如果是,返回true。如果沒有找到,則將這個模和相應的位置加入到map中。最終沒有找到則返回false。

程式碼

public boolean checkSubarraySum(int[] nums, int k) {
    Map<Integer, Integer> map = new HashMap<Integer, Integer>(){{put(0,-1);}};;
    int runningSum = 0;
    for (int i=0;i<nums.length;i++) {
        runningSum += nums[i];
        if (k != 0) runningSum %= k; 
        Integer prev = map.get(runningSum);
        if (prev != null) {
            if (i - prev > 1) return true;
        }
        else map.put(runningSum, i);
    }
    return false;
}

O(n)時間複雜度,O(k)空間複雜度(C++)set

C++版本,用set代替map的作用。unordered_set,無序set。一旦在set找到已有的模,則返回true。

程式碼

class Solution {
public:
    bool checkSubarraySum(vector<int>& nums, int k) {
        int n = nums.size(), sum = 0, pre = 0;
        unordered_set<int> modk;
        for (int i = 0; i < n; ++i) {
            sum += nums[i];
            int mod = k == 0 ? sum : sum % k;
            if (modk.count(mod)) return true;
            modk.insert(pre);
            pre = mod;
        }
        return false;
    }
};