Leetcode——523. Continuous Subarray Sum

来源:互联网 发布:天猫魔盒看电影软件 编辑:程序博客网 时间:2024/04/29 16:23

Description

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=6
Output: True
Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.

Example 2:

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:

The length of the array won't exceed 10,000.You may assume the sum of all the numbers is in the range of a signed 32-bit integer.

Two Solutions

One is O(N^2)
先求一个累计和,然后判断这累计和里面连续的几个数的和是否满足是k的倍数。时间复杂度为O(N^2)。很容易想到!

class Solution {public:    bool checkSubarraySum(vector<int>& nums, int k) {//忘了考虑:k=0,nums是00这种满足情况,其他的k=0,nums和中没有0,是不满足的。以及k=负数情况        int len=nums.size();        if(len<2) return false;        vector<long>sum(len,0);        sum[0]=nums[0];        for(int i=1;i<len;i++)             sum[i]=sum[i-1]+nums[i];        for(int i=0;i<len;i++)        {            for(int j=i+1;j<len;j++)            {                int temp=sum[j]-sum[i]+nums[i];//calculate the sum of nums[i——j],inlcude i,j                if(k==0)                {                    if(temp==0)                        return true;                    else                        continue;                }                else if(temp%k==0)                    return true;            }        }        return false;    }};

the other is using unordered_map,O(n) time complexity,O(n) space complexity!
Look Down!

class Solution {public:    bool checkSubarraySum(vector<int>& nums, int k) {        int len=nums.size();        if(len<=1) return false;        unordered_map<int,bool> A;        int sum=0;        for(int i=0;i<len;i++)        {            sum=sum+nums[i];            if(k!=0)            {                if(i!=0&&sum!=0&&sum%k==0) return true;//just for two cases: {1,1} 2.  {5,2,4}  5                sum=sum%k;                if(A.find(sum)!=A.end())                    return true;                else                    A[sum]=true;            }            else             {                if(nums[i]==0&&i+1<len&&nums[i+1]==0)                    return true;            }        }        return false;    }};

额外的corner cases真TM烦人!

0 0
原创粉丝点击