問題:數組
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.spa
Example 1:ip
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:rem
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:get
解決:it
① 這道題給了咱們一個數組和一個數字k,讓咱們求是否存在這樣的一個連續的子數組,該子數組的數組之和能夠整除k。io
遍歷全部的子數組,而後利用累加和來快速求和。在獲得每一個子數組之和時,咱們先和k比較,若是相同直接返回true,不然再判斷,若k不爲0,且sum能整除k,一樣返回true,最後遍歷結束返回false。ast
class Solution {//78ms
public boolean checkSubarraySum(int[] nums, int k) {
for (int i = 0;i < nums.length;i ++){
int sum = nums[i];
for (int j = i + 1;j < nums.length;j ++){
sum += nums[j];
if (sum == k) return true;
if (k != 0 && sum % k == 0) return true;
}
}
return false;
}
}function
② 若數字 a 和 b 分別除以數字 c,若獲得的餘數相同,那麼(a - b)一定可以整除 c。class
一、處理k爲0的狀況;二、用HashMap保存sum對k取餘數,若是前序有餘數也爲sum % k的位置,那麼就存在連續子數組和爲k的倍數。
在discuss中看到的。。。。。。。。
class Solution { //13ms public boolean checkSubarraySum(int[] nums, int k) { // 23 2 4 6 7 ===> 23 % 6 ==> 5 % 6 ==> 5 + 2 ==> 7 % 6 ==> 1 + 4 ==> 5 % 6 ==> 5 + 6 ==> 5 % 6 ==> 12 % 6==> 0 HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); map.put(0,-1); int remainingSum = 0; for(int i = 0 ; i < nums.length ; i ++){ remainingSum += nums[i]; if(k != 0) remainingSum %= k; if(map.containsKey(remainingSum)){ int pre = map.get(remainingSum); if(i - pre > 1) return true; }else map.put(remainingSum , i); } return false; } }