思路一:暴力破解,無序陣列排序,排完序之後找到第k個最大的數,排序方法有多種,但是無序陣列排序快排時間複雜度比較低是o(nlogn)
思路二:快速選擇
快速選擇是在快速排序的基礎上進行的優化,快速選擇是把找到的基準點與要找的第k個數的下標做比較,如果正好是第k個最大的數直接返回即可,如果是比基準點大則遞迴右側,小的話則遞迴左側。與快速排序相比可以少遞迴一半的資料。
random random =
newrandom()
;public
intfindkthlargest
(int
nums,
int k)
private
intquickselect
(int
nums,
int idx,
int l,
int r)
return point > idx ?
quickselect
(nums, idx, l, point -1)
:quickselect
(nums, idx, point +
1, r);}
private
intpartition
(int
nums,
int l,
int r)
}swap
(nums,i+
1,r)
;return i +1;
}private
void
swap
(int
nums,
int l,
int r)
int temp = nums[l]
; nums[l]
= nums[r]
; nums[r]
= temp;
}
找到第k個最大的數
一 問題描述 給定乙個陣列,陣列中的資料無序,在乙個陣列中找出其第k個最小的數,例如對於陣列x,x 則其第2個最小的數為2。二 解題思路 本演算法跟快排的思想相似,首先在陣列中選取乙個數centre作為樞紐,將比centre小的數,放到centre的前面將比centre大的數,放到centre的後面...
演算法 尋找第K個最大的數
解題思路 通過快速排序的思想方法,每次隨機獲取指定範圍內乙個樹的排序位置,然後根據這個位置,再重新指定範圍,直到這個位置索引滿足k。class solution else index part nums,left,right return nums k public intpart int nums...
第k個排列數
the set 1,2,3,n contains a total of n unique permutations.by listing and labeling all of the permutations in order,we get the following sequence ie,fo...