第一种暴力解决 O(N^2)
import java.util.Scanner; public class code10_SmallSum { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine().toString(); String[] arr = str.split(" "); int[] b=new int[arr.length]; for(int i=0;i第二种用归并排序的思想解决O(N*logN)
import java.util.Scanner; public class code11_smallSum2 { 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; } // l < r 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] ? (r - p2 + 1) * arr[p1] : 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 void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine().toString(); String[] arr = str.split(" "); int[] b=new int[arr.length]; for(int i=0;i 新创建一个公众号 Rockey小何同学 想相互交流的同学可以关注一下哈! 感谢支持!欢迎分享,转载请注明来源:内存溢出
评论列表(0条)