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:

  1. The length of the array is in range [1, 20,000].
  2. 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 kTwo SumContinuous Subarray SumSubarray Product Less Than KFind Pivot Index.

posted @ 2017-10-31 13:24  Dylan_Java_NYC  阅读(308)  评论(0编辑  收藏  举报