public static void main(String[] args) {
// TODO Auto-generated method stub
int[] array1 = { 2, 3, 3, 5, 6 };
int[] res = getSubarraySum(array1, 8);
for (int i : res) {
System.out.print(i + " ");
}
System.out.println();
int[] array2 = { 2, -3, 3, 5, 6 };
res = getSubarraySum(array2, 8);
for (int i : res) {
System.out.print(i + " ");
}
}
private static int[] getSubarraySum(int[] array, int target) {
int[] res = new int[2];
if (array == null || array.length == 0) {
return res;
}
Map<Integer/*subsum*/, Integer/*index of array*/> map = new HashMap<>();
map.put(0, -1);
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum = sum + array[i];
map.put(sum, i);
if (map.containsKey(sum - target)) {
res[0] = map.get(sum - target) + 1;
res[1] = i;
return res;
}
}
return res;
}
subarray sum
最新推荐文章于 2022-05-04 21:09:15 发布