LeetCode-Subarray Sum Equals K
阿新 • • 發佈:2018-11-01
一、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.
題目大意:給定一個數組和一個k,找出陣列中所有連續元素的和等於k的組合數。
Example 1:
Input:nums = [1,1,1], k = 2 Output: 2
二、Analyzation
在這裡介紹時間複雜度和空間複雜度最優化的方法。定義一個hashmap,其中key放的是從0到當前索引所有元素的和sum,value是對應的sum所出現的次數,為什麼要這麼做呢?
假設當前遍歷到的陣列下標為j,則:
sum[0...j] - sum[0...x] = sum[x + 1...j];//其中k = sum[x + 1...j]
我們從0開始遍歷陣列,不斷累加sum,並檢查map中是否包含值為sum - k的key,如果包含,說明在這之前一定存在一個連續的子序列的值等於k,這時count加一,並將當前的sum放入map中(如果已存在則更新value加一),最後返回count即為所求。
三、Accepted code
class Solution { public int subarraySum(int[] nums, int k) { if (nums == null || nums.length == 0) { return 0; } int sum = 0, count = 0; Map<Integer, Integer> map = new HashMap<>(); map.put(0, 1); for (int i = 0; i < nums.length; i++) { sum += nums[i]; if (map.containsKey(sum - k)) { count += map.get(sum - k); } map.put(sum, map.getOrDefault(sum, 0) + 1); } return count; } }