快排、归并、堆排找第k大数
https://leetcode.cn/problems/kth-largest-element-in-an-array/
func findKthLargest(nums []int, k int) int { //quickPow(0,len(nums)-1,nums) //guibin(0,len(nums)-1,nums) // n:=len(nums) // return nums[n-k] return heatSort(k,nums) } //quickPow 快排 func quickPow(le,ri int,nums []int){ if le>=ri{ return } baseIndex:=findBase(le,ri,nums) quickPow(le,baseIndex-1,nums) quickPow(baseIndex+1,ri,nums) } func findBase(le,ri int,nums []int) int{ base:=nums[le] for le<ri{ for le<ri&&nums[ri]>=base{ ri-- } nums[le]=nums[ri] for le<ri&&nums[le]<base{ le++ } nums[ri]=nums[le] } nums[le]=base return le } // guibin 归并 func guibin(le,ri int,nums []int){ if le>=ri{ return } mid:=(le+ri)/2 guibin(le,mid,nums) guibin(mid+1,ri,nums) mergeNums(le,mid,ri,nums) } func mergeNums(le,mid,ri int,nums []int){ leBegin:=le;leEnd:=mid riBegin:=mid+1;riEnd:=ri tmp:=make([]int,0) for leBegin<=leEnd&&riBegin<=riEnd{ if nums[leBegin]>nums[riBegin]{ tmp=append(tmp,nums[riBegin]) riBegin++ }else{ tmp=append(tmp,nums[leBegin]) leBegin++ } } for riBegin<=riEnd{ tmp=append(tmp,nums[riBegin]) riBegin++ } for leBegin<=leEnd{ tmp=append(tmp,nums[leBegin]) leBegin++ } for i:=range tmp{ nums[le+i]=tmp[i] } } //堆排 var heap []int func heatSort(k int,nums []int) int{ heap=make([]int,0) for i:=range nums{ heap=append(heap,nums[i]) insertHeap() } for i:=1;i<k;i++{ deleteHeap() } return heap[0] } func insertHeap(){ now:=len(heap)-1 for now>0{ root:=(now-1)/2 if heap[now]>=heap[root]{ tmp:=heap[root] heap[root]=heap[now] heap[now]=tmp now=root }else{ break } } } func deleteHeap(){ n:=len(heap)-1 if n<0{ return } heap[0]=heap[n] now:=0 for now*2+1<=n{ le:=now*2+1 ri:=now*2+2 if ri>n||heap[le]>heap[ri]{ if heap[le]>heap[now]{ tmp:=heap[now] heap[now]=heap[le] heap[le]=tmp now=le }else{ break } }else{ if heap[ri]>heap[now]{ tmp:=heap[now] heap[now]=heap[ri] heap[ri]=tmp now=ri }else{ break } } } heap=heap[:n] }
等风起的那一天,我已准备好一切