本文主要是介绍LeetCode560. 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
解题思路及需要注意的点:
代码:
Java:
class Solution {public int subarraySum(int[] nums, int k) {Map<Integer,Integer> map=new HashMap<>();map.put(0,1);//当出现num【j】=k,及num【i】=0的时候有用int sum=0,res=0;for(int j=0;j<nums.length;++j){sum+=nums[j];if(map.containsKey(sum-k)){//说明存在,结果+1res+=map.get(sum-k);}map.put(sum,map.getOrDefault(sum,0)+1);}return res;}
}
Python:
class Solution:def subarraySum(self, nums: List[int], k: int) -> int:map={0:1}sum=0res=0for num in nums:sum+=numres+=map.get(sum-k,0)map[sum]=map.get(sum,0)+1return res
这篇关于LeetCode560. Subarray Sum Equals K的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!