在一个数组中,一个数左边比它小的数的总和,叫数的小和,所有数的小和累加起来,叫数组小和,求数组小和,可以利用归并排序
package com.harrison.class03; public class Code02_SmallSum { public static int smallSum(int[] arr) { if (arr == null || arr.length < 2) { return 0; } return process(arr, 0, arr.length - 1); } public static int process(int[] arr, int L, int R) { if (L == R) { return 0; } int mid = L + ((R - L) >> 1); return process(arr, L, mid)+ process(arr, mid + 1, R)+ merge(arr, L, mid, R); } public static int merge(int[] arr, int L, int M, int R) { int[] help = new int[R - L + 1]; int i = 0; int p1 = L; int p2 = M + 1; int res=0; while (p1 <= M && p2 <= R) { res+=arr[p1]<arr[p2]?arr[p1]*(R-p2+1):0; help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++]; } while (p1 <= M) { help[i++] = arr[p1++]; } while (p2 <= R) { help[i++] = arr[p2++]; } for (i = 0; i < help.length; i++) { arr[L+i] = help[i]; } return res; } public static int comparator(int[] arr) { int res=0; if(arr==null || arr.length<2) { return 0; } for(int i=1; i<arr.length; i++) { for(int j=0; j<i; j++) { res+=arr[j]<arr[i]?arr[j]:0; } } return res; } public static int[] generateRandomArray(int maxSize, int maxValue) { int[] arr = new int[(int) ((maxSize + 1) * Math.random())]; for (int i = 0; i < arr.length; i++) { arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random()); } return arr; } public static int[] copyArray(int[] arr) { if (arr == null) { return null; } int[] res = new int[arr.length]; for (int i = 0; i < arr.length; i++) { res[i] = arr[i]; } return res; } public static void printArray(int[] arr) { if (arr == null) { return; } for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } public static void main(String[] args) { int testTimes=1000000; int maxSize=100; int maxValue=100; boolean succeed=true; for(int i=0; i<testTimes; i++) { int[] arr1=generateRandomArray(maxSize, maxValue); int[] arr2=copyArray(arr1); if(smallSum(arr1)!=comparator(arr2)) { succeed=false; printArray(arr1); printArray(arr2); break; } } System.out.println(succeed?"Nice":"Fucking fucked"); } }