Leetcode 560 Subarry Sum Equals K
Posted qwfand
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 560 Subarry Sum Equals K相关的知识,希望对你有一定的参考价值。
Leetcode 560 Subarry 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].
Sulotions
approach1: Brute Force
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int n=nums.size();
int tmp;
int count=0;
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
tmp=0;
for(int k=i;k<=j;k++)
tmp+=nums[k];
if(tmp==k)
count++;
}
}
return count;
}
};
approach2:Using Cummulative sum
定义sum[0,i] 为第0项到第i-1项的和,那么第i到j项的和可表示为 sum[i,j+1]=sum[0,j+1]-sum[0,i]
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int n=nums.size();
int sum[n+1];
int tmp=0;
for(int i=0;i<n;i++)
{
sum[i]=tmp;
tmp+=nums[i];
}
sum[n]=tmp;
int count=0;
for(int i=0;i<n;i++)
for(int j=i+1;j<=n;j++)
if(sum[j]-sum[i]==k)
count++;
return count;
}
};
分析:
时间复杂度:O(N^2)
空间复杂度:O(N)
approach3:Using Cummulative sum using O(1) space
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int n=nums.size();
int tmp;
int count=0;
for(int i=0;i<n;i++)
{
tmp=0;
for(int j=i;j<n;j++)
{
tmp+=nums[j];
if(tmp==k)
count++;
}
}
return count;
}
};
分析:
时间复杂度:O(N^2)
空间复杂度:O(1)
approach4:Using hashmap
借鉴approach2的方法,在第一遍求解sum[0,i]的时候,如果前面存在一个j使得sum[0,j]=k-sum[0,i]的话,是不是就有sum[i,j]=k呢?我们把sum[i]作为Key,sum[i]出现的次数作为value存入一个hashmap或者hashtable中,就可以直接通过sum[0,j]找到该和出现的次数。
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
dic={0:1}
tmp=0
count=0
for i in nums:
tmp+=i;
if tmp-k in dic:
count+=dic[tmp-k]
dic[tmp]=dic.get(tmp,0)+1
return count
分析:
时间复杂度:O(N)
空间复杂度:O(N)
参考链接
以上是关于Leetcode 560 Subarry Sum Equals K的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode 560. Subarray Sum Equals K]
Leetcode 560. Subarray Sum Equals K
[leetcode]Map-560. Subarray Sum Equals K
[LeetCode] 560. Subarray Sum Equals K_Medium