Last active
December 21, 2017 01:21
-
-
Save aquawj/9f4ed1876c14b4ebff7411db76c83af7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int subarraySum(int[] nums, int k){ | |
if( nums == null || nums.length ==0){ | |
return 0; | |
} | |
int sum = 0, count = 0; | |
HashMap<Integer,Integer> map = new HashMap<>(); //map存presum和其出现的次数<presum, frequency of presum> | |
map.put(0, 1); | |
for(int i = 0; i < nums.length; i++){ | |
sum += nums[i]; | |
if(map.containsKey(sum - k)){ //关键句!现在找到的是后面的sum后,如果前面存在一个sum前,使sum后-sum前=k,满足条件。故寻找sum-k | |
count += map.get(sum - k); //将其出现的次数都加上 | |
} | |
if(map.containsKey(sum)){ //还没找到匹配的,就正常put进去:已存在的,频次+1,不存在的,频次为1 | |
map.put(sum, map.get(sum) + 1); | |
}else{ //可以将if-else两种情况简化为一句: map.put(sum, map.getOrDefault(sum, 0) + 1); | |
map.put(sum, 1); | |
} | |
//map.put(sum, map.getOrDefault(sum, 0) + 1); 可以把上面if else合并为这一句 | |
} | |
return count; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment