💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
Find the**k**th largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. **Example 1:** ~~~ Input: [3,2,1,5,6,4] and k = 2 Output: 5 ~~~ **Example 2:** ~~~ Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4 ~~~ **Note:** You may assume k is always valid, 1 ≤ k ≤ array's length. ``` 利用冒泡排序找, 冒泡排序的原理就是for循环,每次找到最大的值,放在数组的末尾。 var findKthLargest = function(arr, k) { let len = arr.length - 1 //外层循环K次 for (let i = len, tmp; i > len - k; i--) { // 内层循环i次,找出剩下的最大的值,将最大的放末尾 for (let j = 0; j < i; j++) { if (arr[j] > arr[j + 1]) { tmp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = tmp } } } // arr[len+1-k] return arr[len - (k - 1)] }; ``` ``` var findKthLargest = function(arr, k) { return arr.sort((a, b) => b - a)[k - 1] } ```