Subarray Sum Equals K
阿新 • • 發佈:2018-12-11
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
題目理解:
給定一個字串,問有多少個連續子串的和等於k
解題思路:
使用一個字典,key是子陣列nums(0 ~ i)的和,value是這個和出現的次數,因為陣列中的數可能有負數,因此可能nums(0 ~ m)和nums(0 ~ n)的和是相等的,遍歷這個陣列,在看到nums[i + 1]的時候,nums[i+1] - k出現的次數,就是nums(x ~ i+1)和為k的次數
程式碼如下:
class Solution { public int subarraySum(int[] nums, int k) { Map<Integer, Integer> left = new HashMap<Integer, Integer>(); left.put(0, 1); int sum = 0, res = 0; for(int num : nums) { sum += num; int key = sum - k; if(left.containsKey(key)) res += left.get(key); left.put(sum, left.getOrDefault(sum, 0) + 1); } return res; } }