LeetCode

来源:互联网 发布:中电数据官网 编辑:程序博客网 时间:2024/06/05 21:04

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.

Example 1:

Input: [23, 2, 4, 6, 7],  k=6Output: TrueExplanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.

Example 2:

Input: [23, 2, 6, 4, 7],  k=6Output: TrueExplanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42.

Note:

  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.

Subscribe to see which companies asked this question.


题意:给出一个数组和k值,求是否存在一个最长的子串和是k的倍数(子串长度大于1)

思路:唔,我实在不明白这题为啥划到dp里边了,想半天无从下手。网上大神给了一个o(n)的做法,统计前缀和%k,用map查询是否出现过这个值。出现过的话直接相减判断就好了,没出现过就丢进map里。服。


class Solution {public:    bool checkSubarraySum(vector<int>& a, int k) {        map<int, int> m;        m.clear();        int sum = 0;        int len = a.size();        m[0] = -1;        for (int i = 0; i < len; i++) {            sum += a[i];            if (k) sum %= k;            if (m.find(sum) != m.end()) {                if (i - m[sum] > 1) return true;            }            else m[sum] = i;        }        return false;    }};


0 0
原创粉丝点击