{2,5,1,1,1,1,4,3,7,5,7} 比如这数组,分为四份,每份的和相同,分割点不算,分为{2,5} {1,1,1,4},{7},{7}.。设计的函数时间复杂度不超过O(n)
思路:用一个map<前n个数的和,n>记录一下,用一个数组记录一个前n个数的和,然后其实找第一个位置在哪里就行了,后面两个点的位置可以直接依赖这个map和数组计算出来,复杂度O(1)。找第一个点的复杂度O(n).
1 package test2; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 public class Test4sum { 7 8 public static void main(String[] args){ 9 int[] input = {2,5,1,1,1,1,4,3,7,5,7}; 10 int[] sums = new int[input.length]; 11 Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>(); 12 13 int tmp = 0; 14 for (int i = 0; i < input.length; ++i) { 15 tmp += input[i]; 16 sums[i] = tmp; 17 hashMap.put(tmp, i); 18 } 19 20 for (int pos1 = 1; pos1 < input.length; ++pos1) { 21 int sum = sums[pos1] - input[pos1]; 22 if (hashMap.containsKey(sum + sums[pos1])) { 23 int pos2 = hashMap.get(sum + sums[pos1]) + 1; 24 if (pos2 < input.length && hashMap.containsKey(sum + sums[pos2])) { 25 int pos3 = hashMap.get(sum + sums[pos2]) + 1; 26 if (pos3 < input.length && sums[sums.length - 1] - sums[pos3] == sum) { 27 System.out.println("result:"+pos1 + "---"+pos2+"----"+pos3); 28 return; 29 } 30 } 31 } 32 } 33 } 34 }