题目
非负整数数组中,连续子数组(子数组长度最小为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;
}
};