LeetCode 560. Subarray Sum Equals K
原题链接在这里:https://leetcode.com/problems/subarray-sum-equals-k/description/
题目:
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].
题解:
计算subarray的和为k的个数.
保存从头到当前值和sum 以及 对应这个和的个数. 若是之前出现了sum-k说明这一段相加就是k. 更新和.
Note: 初始HashMap<Integer, Integer> hm 时需要先把和为0的情况加进去. 最开始什么都没有, 所以hm需要加上<0,1>这个对应关系.
Time Complexity: O(nums.length).
Space: O(nums.length).
AC Java:
1 class Solution { 2 public int subarraySum(int[] nums, int k) { 3 if(nums == null || nums.length == 0){ 4 return 0; 5 } 6 7 HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); 8 hm.put(0, 1); 9 int res = 0; 10 int sum = 0; 11 for(int num : nums){ 12 sum += num; 13 if(hm.containsKey(sum - k)){ 14 res += hm.get(sum - k); 15 } 16 17 hm.put(sum, hm.getOrDefault(sum, 0)+1); 18 } 19 return res; 20 } 21 }
类似Maximum Size Subarray Sum Equals k, Two Sum, Continuous Subarray Sum, Subarray Product Less Than K, Find Pivot Index.
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步