日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

牛客(35)数组中的逆序对

發(fā)布時(shí)間:2025/5/22 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 牛客(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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。