Links: https://leetcode-cn.com/problems/continuous-subarray-sum
Given a non-negative number of arrays and a certain integer k, write a function to determine if the array is comprising successive sub-arrays, the size of at least 2, the total is a multiple of k, i.e., the sum of n * k, wherein n is an integer.
Example 1:
Input: [23,2,4,6,7], k = 6
Output: True
Explanation: [2,4] is a sub-array of size 2 and 6, and.
Example 2:
Input: [23,2,6,4,7], k = 6
Output: True
Explanation: [23,2,6,4,7] subarray with a size of 5 and 42, and.
Description:
Length of the array does not exceed 10,000.
You can think of the sum of all the numbers in the range of 32-bit signed integer.
Solution 1: Optimization of violence
And the first pre-prefix, and violence enumerate all possible scale interval [i, j], and then the prefix obtained by subtracting two sections and then judges whether n% k == sum. The time complexity of O (n2)
Note that the sum = 0 and k = 0, they might divide by zero anomaly.
class Solution { public: bool checkSubarraySum(vector<int>& nums, int k) { int n=nums.size(); vector<int> pre_sum(n+1); for(int i=1;i<=n;i++){ pre_sum[i]+=pre_sum[i-1]+nums[i-1]; } for(int i=0;i<n-1;i++){ for(int j=i+1;j<n;j++){ int sum=pre_sum[j+1]-pre_sum[i]; if(sum==0 ||(k && sum%k==0))return true; } } return false; } };
Solution 2: hash tables buckle lead independent solution to a problem ----
In this method, we use a HashMap to save and to accumulate until the i-th element, but we take the remainder of this prefix and divided by k. For the following reasons:
We iterate over a given array, which records up to the present position of the sum% k. Once we have found a new sum% k values (i.e., the value in the HashMap not), we intend to insert a record HashMap (sum% k, i)
Now, suppose sum% k of the i-th position is rem. If any sub-array to the left end point and i is a multiple of k, in this example, position j, then stored in a HashMap j-th element value (rem + n * k)% k, where n is a integer greater than zero. We will find (rem + n * k)% k = rem, which is saved with the i-th element to the same value in the HashMap.
Based on this observation, we conclude that: whenever the value of the sum% k have been placed in a HashMap represents two indices i and j, between them and the elements is an integer multiple of k. Therefore, as long as the HashMap with the same sum% k, we can return to True directly.
class Solution { public: bool checkSubarraySum(vector<int>& nums, int k) { map<int,int> mp; int presum=0; mp[0]=-1; //? for(int i=0;i<nums.size();i++){ presum+=nums[i]; // if(k!=0) presum%=k; if(1 == mp.count(presum)){ if(i-mp[presum]>1) // return true; } else mp[presum]=i; } return false; } };