本文主要是介绍归并求逆序数对,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
c#
- bobo
bobo
慢慢分析中
public class Solution {public int ReversePairs(int[] nums) {int[] temp = new int[nums.Length];Array.Copy(nums, 0, temp, 0, nums.Length);return Sort(nums, 0, nums.Length - 1, temp);}private static int Sort<T>(T[] arr, int l, int r, T[] temp) where T : IComparable{if (l >= r) return 0;int res = 0;int mid = l + (r - l) / 2;res += Sort(arr, l, mid, temp);res += Sort(arr, mid + 1, r, temp);if (arr[mid].CompareTo(arr[mid + 1]) > 0)res += Merge(arr, l, mid, r, temp);return res;}private static int Merge<T>(T[] arr, int l, int mid, int r, T[] temp) where T : IComparable{int length = r + 1 - l;Array.Copy(arr, l, temp, l, length);int i = l, j = mid + 1, res = 0;for (int k = l; k <= r; k++){if (i > mid){arr[k] = temp[j]; ++j;}else if (j > r){arr[k] = temp[i]; ++i;}else if (temp[i].CompareTo(temp[j]) <= 0){arr[k] = temp[i]; ++i;}else{res += mid - i + 1;arr[k] = temp[j]; ++j;}}return res;}
}
这篇关于归并求逆序数对的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!