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