Array 类型的题目,用hashmap 可以找到特定和的组合:
1,求两者之和为固定某数
if (map.contains(sum - curtValue)) {
index1 = map.get(sum - curtValue);
index2 = curtIndex;
break;
}
2,求两个index之间的所有数的和为某数
if (map.contains(curtSum - sum)) {
index1 = map.get(curtSum - sum);
index2 = curtIndex;
break;
}
题目:
138. Subarray Sum
Given an integer array, find a subarray where the sum of numbers is zero. Your code should return the index of the first number and the index of the last number.
Example
Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].
Notice
There is at least one subarray that it's sum equals to zero.
code:
第一步put(0,-1)是给从第一位开始的子数列设置原点,整体思路是从某一位开始,往后几位加起来和为0,也就是这一位数字重复出现了,那么这一位后面开始1位(也就是mp.get()+1),到现在循环到的第i位,是和为0的子数列。
网友评论