牛客(35)数组中的逆序对
生活随笔
收集整理的這篇文章主要介紹了
牛客(35)数组中的逆序对
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
// 題目描述
// 在數組中的兩個數字,如果前面一個數字大于后面的數字,則這兩個數字組成一個逆序對。
// 輸入一個數組,求出這個數組中的逆序對的總數P。并將P對1000000007取模的結果輸出。 即輸出P%1000000007}// 題目保證輸入的數組中沒有的相同的數字
//
// 數據范圍:
//
// 對于%50的數據,size<=10^4
//
// 對于%75的數據,size<=10^5
//
// 對于%100的數據,size<=2*10^5// public static int InversePairs(int[] array) {
超時
// int count = 0;
// for (int i=0; i<array.length;i++){
// for (int j=i+1;j<array.length;j++){
// if (array[i]>=array[j]){
// count++;
// }
// }
// }
// return count%1000000007;
// }public static int InversePairs(int[] arr) {int[] temp = new int[arr.length];//在排序前,先建好一個長度等于原數組長度的臨時數組,避免遞歸中頻繁開辟空間return sort(arr, 0, arr.length - 1, temp);}private static int sort(int[] arr, int left, int right, int[] temp) {if (left >= right) {return 0;}int count = 0;int mid = (left + right) / 2;int leftCount = sort(arr, left, mid, temp);//左邊歸并排序,使得左子序列有序int rightCount = sort(arr, mid + 1, right, temp);//右邊歸并排序,使得右子序列有序int i= mid;int j=right;while (i>=left&&j>mid){if (arr[i]>arr[j]){count += j-mid;//不加判斷通過50%if(count>=1000000007)//數值過大求余
{count%=1000000007;}i--;}else{j--;}}merge(arr, left, mid, right, temp);//將兩個有序子數組合并操作//75%通過
// return count + leftCount + rightCount;return (count + leftCount + rightCount)%1000000007;}private static void merge(int[] arr, int left, int mid, int right, int[] temp) {int i = left;//左序列指針int j = mid + 1;//右序列指針int t = 0;//臨時數組指針while (i <= mid && j <= right) {if (arr[i] <= arr[j]) {temp[t++] = arr[i++];} else {temp[t++] = arr[j++];}}while (i <= mid) {//將左邊剩余元素填充進temp中temp[t++] = arr[i++];}while (j <= right) {//將右序列剩余元素填充進temp中temp[t++] = arr[j++];}t = 0;//將temp中的元素全部拷貝到原數組中while (left <= right) {arr[left++] = temp[t++];}}
?
轉載于:https://www.cnblogs.com/kaibing/p/9046474.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的牛客(35)数组中的逆序对的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue-video-player集成vi
- 下一篇: 开陶艺店需要准备什么 创业者开店之前得了