求第K大的数—利用快速排序的思想
class Solution {
public:
int partition(vector<int>& num, int l, int r){
swap(num[l],num[l+rand()%(r-l+1)]);
int x = num[l];
int i=l+1, j=r;
while(i<=j){
while(i<=r&&num[i]<=x){
i++;
}
while(num[j]>x){
j--;
}
if(i>=j) break;
swap(num[i],num[j]);
}
swap(num[l],num[j]);
return j;
}
int find(vector<int>& num, int k){
int l=0,r=num.size()-1;
while(l<=r){
int pos = partition(num,l,r);
if(pos==k-1) return num[pos];
else if(pos>k-1){
r = pos-1;
}else{
l = pos+1;
}
}
return -1;
}
int findKthLargest(vector<int>& nums, int k) {
return find(nums,nums.size()-k+1);
}
};
求逆序对的数量-归并排序
思路是:一个数组逆序对的数量等于左部分+右部分+横跨中间的逆序对数量
#include<iostream>
using namespace std;
int merge_sort(int *num, int *tmp, int l, int r){
if(l==r) return 0;
int mid = (l+r)/2;
int res = merge_sort(num,tmp,l,mid) + merge_sort(num,tmp,mid+1,r);
for(int i=l;i<=r;i++) tmp[i]=num[i];
int i = l, j = mid+1;
for(int k=l;k<=r;k++){
if(i==mid+1){
num[k]=tmp[j++];
}else if(j==r+1){
num[k]=tmp[i++];
}else if(num[i]>num[j]){
num[k]=tmp[j++];
res += mid-i+1;
}else{
num[k]=tmp[i++];
}
}
return res;
}
int main(){
int n;
scanf("%d",&n);
int num[n];
int tmp[n];
for(int i=0;i<n;i++) scanf("%d",&num[i]);
int result = merge_sort(num,tmp,0,n-1);
cout<<result;
//for(int i=0;i<n;i++) printf("%d ",num[i]);
return 0;
}