判断是否存在连续子数组之和能够整除k Continuous Subarray Sum

问题:数组

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

  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.

解决:it

①  这道题给了咱们一个数组和一个数字k,让咱们求是否存在这样的一个连续的子数组,该子数组的数组之和能够整除kio

遍历全部的子数组,而后利用累加和来快速求和。在获得每一个子数组之和时,咱们先和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;     } }

相关文章
相关标签/搜索