赞
踩
在一个数组中,将每一个比当前数小的左边的数累加起来称作这个数组的小和(small Sum)。求该数组的小和。
int[] array = new int[] {1, 3, 4, 2, 5};
smallSum = 1 + (1 + 3) + 1 + (1 + 3 + 4 + 2) //==> smallSum = 16
将小和问题转换为右边有多少个数比它大(基于MergeSort)
public class code02_SmallSum { public static void main(String[] args) { System.out.println(smallSum(new int[]{1, 3, 4, 2, 5})); } public static int smallSum(int[] array) { if (array == null || array.length < 2) { return 0; } return process(array, 0, array.length - 1); } public static int process(int[] array, int L, int R) { if (L == R) { return 0; } int middle = L + ((R - L) >> 1); return process(array, L, middle) + process(array, middle + 1, R) + merge(array, L, middle, R); } public static int merge(int[] array, int L, int middle, int R) { int[] tmp = new int[R - L + 1]; int i = 0; int p1 = L; int p2 = middle + 1; int sum = 0; while (p1 <= middle && p2 <= R) { sum += array[p1] < array[p2] ? array[p1] * (R - p2 + 1) : 0; tmp[i++] = array[p1] < array[p2] ? array[p1++] : array[p2++]; } while (p1 <= middle) { tmp[i++] = array[p1++]; } while (p2 <= R) { tmp[i++] = array[p2++]; } System.arraycopy(tmp, 0, array, L, tmp.length); return sum; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。