LeetCode 523. Continuous Subarray sum和 525. Contiguous Array和560. Subarray Sum Equals K

leetcode题解 以下三题解法非常类似
总结:523. Continuous Subarray Sum 求最长连续子序列的和是k的倍数
525. Contiguous Array 求最长连续子序列中1的个数和0的个数相等
560. Subarray Sum Equals K 连续子序列中和为k的个数有多少
53. Maximum Subarray 连续子序列的最大和
152. Maximum Product Subarray 连续子序列乘积最大

523. 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.

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.

题意

给定一个整型数组和目标值k,写一个函数检查数组中是否存在一个长度至少为2的连续子序列,其和是k的整数倍。

思路1

从子序列长度为2到数组长度遍历,各个子序列的和
比较直观的想法是从长度2开始依次计算所有子数组的相加和,判断其是否是k的倍数。这里不必每轮循环都重新计算相加和,可以通过动态规划的思想在上一轮循环的基础上再加一个数组元素来计算当前循环中的相加和。

代码

class Solution {
public:
    bool checkSubarraySum(vector<int>& nums, int k) {
        vector<int> sum(nums.begin(),nums.end());
        int length = nums.size();

        for(int len = 2;len <= length; len++)
        {
            for(int i = 0; i <= length - len;i++)
            {

                sum[i] += nums[i+len-1];  //从连续子序列2开始累加,之后长度为3的的子序列和可以直接使用长度为2的值,不必从头遍历
                                          //技巧:起点位置i+区间长度l-1
                if(sum[i] == 0)
                    return true;    //解决[0,0] 0 的特殊输入
                if(k != 0 && ((sum[i] % k) == 0))  
                    return true;
            }
        }
        return false;
    }
};

结果

这里写图片描述

思路2

遍历整个数组,依次加当前数组元素并将相加和求余k,求余结果只有0~k-1这k中情况,将求余结果存入Hash Table中。如果遍历到当前位置求余结果已经在Hash Table中,表明从上一求余结果相同的位置到当前位置的子数组相加和是k的倍数,否则将求余结果存入Hash Table。这里同样需要注意上面提到的边界情况,代码中hash[0] = -1这行即为了便于边界情况的处理。具体代码:
技巧:若数字suma和sumb分别除以数字k,若得到的余数相同,那么(suma-sumb)必定能够整除k.
suma % k == sumb % k ==> (suma-sumb)%k == 0

a b c d e,(a+b)%mod=k,(a+b+c+d+e)%mod也=k,那么(c+d+e)%mod=0,即该子序列是mod的整数倍数。

    class Solution {  
    public:  
        bool checkSubarraySum(vector<int>& nums, int k) {  
            unordered_map<int, int> hash;  
            int sum = 0;  

            hash[0] = -1;  
            for(int i=0; i<nums.size(); ++i) {  
                sum += nums[i];  
                if(k) sum %= k;  
                if(hash.find(sum) != hash.end()) {  
                    if(i-hash[sum] > 1) return true;  
                }  
                else hash[sum] = i;  
            }  

            return false;  
        }  
    };  

525. Contiguous Array

题目

Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.

Example 1:

Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.

Example 2:

Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.

Note: The length of the given binary array will not exceed 50,000.


题意

给定一个数组只包含0,1,找出最长的连续子序列使得0和1的个数相同
如:输入:010011 输出:6


思路

和523类似,使用思路2
这里需要做一个处理,1-》1,0-》-1。
我们需要用到一个sum,遇到1就加1,遇到0,就减1,这样如果某个子数组和为0,就说明0和1的个数相等。知道了这一点,我们用一个哈希表建立子数组之和跟结尾位置的坐标之间的映射。如果某个子数组之和在哈希表里存在了,说明当前子数组减去哈希表中存的那个子数字,得到的结果是中间一段子数组之和,必然为0,说明0和1的个数相等,我们更新结果res

代码

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        unordered_map<int,int> hash;
        hash[0] = -1;

        int sum = 0;
        int res = 0;
        for(int i=0;i < nums.size();i++)
        {
            sum += (nums[i] == 1)?1:-1;  //注意三目运算符的写法              
            if(hash.count(sum))
                res = max(res,i-hash[sum]);  //更新子序列的最大的长度
            else
                hash[sum] = i;                    
        }

        return res;
    }
};

560. Subarray Sum Equals K

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:

Input:nums = [1,1,1], k = 2
Output: 2

Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

题意

给定一个数组,和数字k,求有多少个连续子序列的和等于k

思路1

类似523思路1,遍历各个子序列长度从1到nums.size()并求和,优化

代码

需要修改sum的赋值,对于长度为1 == k的情况考虑

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {        
       vector<int> sum;
        int res = 0;
        int count = 0;
        for (int len = 1; len <= nums.size(); len++)
        {
            for (int i = 0; i <= nums.size() - len;i++)
            {
                if (len == 1) 
                {
                    sum.push_back(nums[i]);
                }
                else
                    sum[i] += nums[i + len - 1];
                if (sum[i] == k)   //sum[i]表示以i为起点,len为长度的连续和
                    count++;
            }
        }

        return count;
    }
};

能ac但是效率很低

思路二

hash建立索引,感慨大佬的思路
论坛上大家比较推崇的其实是这种解法,用一个哈希表来建立连续子数组之和跟其出现次数之间的映射,初始化要加入{0,1}这对映射,这是为啥呢,因为我们的解题思路是遍历数组中的数字,用sum来记录到当前位置的累加和,我们建立哈希表的目的是为了让我们可以快速的查找sum-k是否存在,即是否有连续子数组的和为sum-k,如果存在的话,那么和为k的子数组一定也存在。
解释初始化hash{0,1}的原因,这样当sum刚好为k的时候,那么数组从起始到当前位置的这段子数组的和就是k,满足题意,如果哈希表中实现没有m[0]项的话,这个符合题意的结果就无法累加到结果res中,这就是初始化的用途。上面讲解的内容顺带着也把for循环中的内容解释了,这里就不多阐述了,有疑问的童鞋请在评论区留言哈,参见代码如下:

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {        
        unordered_map<int,int> hash;
        hash[0] = 1;
        int sum = 0;
        int cnt = 0;
        for(int i = 0; i < nums.size(); i++)
        {
            sum += nums[i];
            cnt += hash[sum - k];
            hash[sum]++;
        }
        return cnt;
    }
};

152. Maximum Product Subarray

class Solution {
public:
    int maxProduct(vector<int>& nums) {
      if(nums.empty())
          return 0;
        int res = nums[0];   //存储到目前为止最大的乘积
        int imax = nums[0];  //存储当前的最大最小值,到nums[i]为止
        int imin = nums[0];
        for(int i=1;i<nums.size();i++)
        {
            if(nums[i]<0)
                swap(imax,imin);  //乘以一个负数使得大数变小,小数变大
            //到nums[i]为止的,当前的最大/最小值可能是它本身或者是之前的最大/最小值*它本身
            imax = max(nums[i],imax * nums[i]);
            imin = min(nums[i],imin * nums[i]);

            res = max(res,imax);
        }

        return res;
        /*int res =0x80000000;        
        vector<int> multiVec;

       for(int len = 1; len <= nums.size(); len++)
       {                      
           for(int i=0; i <= nums.size()-len; i++)
           {
               if(len == 1)
                   multiVec.push_back(nums[i]);
               else
                   multiVec[i] *= nums[i+len-1];

               res = max(res,multiVec[i]);
           }
       }
        return res;
        */
        //超时
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值